使用Http通信主要有get與post兩種方式,本文分別介紹使用Http的Get與Post方式與服務器通信;使用HttpClient進行Get或Post通信
詳細代碼:LearnHttp ??LearnHttpClient
1.使用Http的Get方法讀取數據
使用get方法,調用有道翻譯API,獲取輸入文本的相應翻譯
網絡請求較耗時,應使用異步操作。在button的cllick事件中新建AsyncTask,復寫必須復寫的doInBackground方法。
newAsyncTask(){
@Override
protectedStringdoInBackground(String... params) {
在doInBackground方法中,執行http的get操作。創建url對象,打開urlConnection,讀寫方式讀取獲得的網絡數據,StringBuffer儲存。記得讀寫完成后返回字符串
@Override
protectedStringdoInBackground(String... params) {
try{
//用參數中的url創建url對象
URL url =newURL(params[0]);
URLConnection connection = url.openConnection();
//字節流
InputStream is =? connection.getInputStream();
//指定編碼方式,字節流轉字符流
InputStreamReader isr? =newInputStreamReader(is,"UTF-8");
//帶緩沖區的reader
BufferedReader br? =newBufferedReader(isr);
String line;
StringBuffer sb =newStringBuffer();
while((line = br.readLine()) !=null){
sb.append(line);
}
br.close();
isr.close();
is.close();
//讀寫完成后返回字符串
returnsb.toString();
}catch(MalformedURLException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
重寫onPostExecute方法,參數為doInBackground返回的字符串。解析json對象,添加入adapter,為listView設置adapter
try{
JSONObject root =newJSONObject(s);
JSONObject basic = root.getJSONObject("basic");
adapter.add("音標:"+basic.getString("phonetic"));
adapter.add("基本解釋:");
JSONArray explains = basic.getJSONArray("explains");
for(inti=0;i
adapter.add(explains.getString(i));
}
lv.setAdapter(adapter);
}catch(JSONException e) {
e.printStackTrace();
}
調用AsyncTask的execute方法,參數為傳給doInBackground的url,此處為復制過來的有道翻譯的api,在api合適的位置添入輸入文本中的內容
execute("http://fanyi.youdao.com/openapi.do?keyfrom=baolvlvLearnHttp&key=1094693720&type=data&doctype=json&version=1.1&q="+et.getText());
get方法將需要傳遞給服務器的數據放置在url內部http://fanyi.youdao.com/openapi.do?keyfrom=baolvlvLearnHttp&key=1094693720&type=data&doctype=json&version=1.1&q=
?前為真實的url,?后為傳遞給服務器的數據 ?區分真實網址與傳入數據
一般的互聯網操作包括瀏覽器在內都是使用get方法
2.使用Http的post方式與網絡交互通信
get方式在url的內部傳遞數據,post方式通過connection的輸出流傳遞數據,默認以get 方式傳遞數據
創建HttpURLConnention,將url.openConnention()強制轉換為HttpURLConnention
//用參數中的url創建url對象
URL url =newURL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
創建輸出流,通過輸出流寫入向服務器傳遞的數據
OutputStream os = connection.getOutputStream();
//創建writer
OutputStreamWriter osw =newOutputStreamWriter(os,"UTF-8");
//創建帶緩沖區的writer,可以寫入行
BufferedWriter bw =newBufferedWriter(osw);
bw.write("keyfrom=baolvlvLearnHttp&key=1094693720&type=data&doctype=json&version=1.1&q="+result);
bw.flush();
設置connection,使connection可以向服務器傳遞數據,設置請求方式為post
//配置connection,使當前的connection可以向服務器輸出數據
connection.setDoOutput(true);
// connection.setDoInput默認為true
connection.setDoInput(true);
//設置connection當前的請求方式
connection.setRequestMethod("POST”);
數據讀取的方式與get完全相同
3.使用HttpClient進行get方式通信
HttpClient------------客戶端http通信實現庫,發送和接收http報文
HttpClient在 android sdk23以上不再支持,如果要使用,在build.gradle(Module:app)中android括號中添加useLibrary
android{
useLibrary‘org.apache.http.legacy’
}
聲明HttpClient,在onCreate函數中實例化
//聲明HttpClient
HttpClientclient;
//實例化HttpClient
client=newDefaultHttpClient();
自定義readNet用于讀取url進行請求,新建異步操作,復寫doInBackground方法,執行請求的url
public voidreadNet(String Url){
newAsyncTask(){
@Override
protectedStringdoInBackground(String... params) {
}.execute(Url);
doInBackground()方法中,接收url,創建繼承自HttpRequest的HttpGet對象
//創建HttpGet對象,HttpGet繼承自HttpRequest
HttpGet get =newHttpGet(urlString);
client執行execute(get)得到HttpResponse對象
//HttpClient執行HttpGet獲得HttpResponse對象
HttpResponse response =client.execute(get);
通過response.getEntity()獲取請求結果,通過EntityUtils轉換為string,返回結果
String value = EntityUtils.toString(response.getEntity());
4.使用HttpClient進行post方式通信
使用post方式通信時,url與參數的值分開寫,需要為post對象設置Entity
由于服務器端需要提交表單,所以
調用讀取url的方法的參數傳入兩個字符串,分別為主url和參數鍵值對中的值
readNet("http://10.0.2.2:8080/MyWebTest/Do?name=",et.getText().toString());
在doInBackground方法中,獲取參數數組中的第一個參數(主url),創建HttpPost對象
//獲取數組中的第一個參數,為真實的url
String urlString? = params[0];
//創建httpPost對象
HttpPost post =newHttpPost(urlString);
創建list對象,范型為BasicNameValuePair,用于儲存請求參數的鍵值對,添入請求的鍵和參數數組的第二個元素
//基礎鍵值對
List list =newArrayList();
list.add(newBasicNameValuePair("name",params[0]));
創建UrlEncodedFromEntity對象,將list轉為Entity的表單對象,為post設置entity
//基礎鍵值對
List list =newArrayList();
list.add(newBasicNameValuePair("name",params[1]));
//將list轉為Entity
post.setEntity(newUrlEncodedFormEntity(list));
client執行post獲取response,response getEntity()獲取entity后,轉為String
HttpResponse response =client.execute(post);
String value = EntityUtils.toString(response.getEntity());