Android / php / get /post / 通信



GET 方式 


//先將參數放入List,再對參數進行URL編碼 

List params = new LinkedList(); 

params.add(new BasicNameValuePair("param1", "param1")); 

params.add(new BasicNameValuePair("param2", "value2")); 


//baseUrl 

String path = "http://ubs.free4lab.com/php/method.php"; 

//將URL與參數拼接 

HttpGet getMethod = new HttpGet(path + "?" + URLEncodedUtils.format(params, "UTF-8")); 


HttpClient httpClient = new DefaultHttpClient(); 

try { 

HttpResponse response = httpClient.execute(getMethod); //發起GET請求 

Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應碼 

Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//獲取服務器響應內容 

} catch (ClientProtocolException e) { 

e.printStackTrace(); 

} catch (IOException e) { 

e.printStackTrace(); 


POST方式 


//先將參數放入List 

params = new LinkedList(); 

params.add(new BasicNameValuePair("param1", "Post方法")); 

params.add(new BasicNameValuePair("param2", "第二個參數")); 


try { 

HttpPost postMethod = new HttpPost(baseUrl); 

postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //將參數填入POST Entity中 


HttpResponse response = httpClient.execute(postMethod); //執行POST方法 

Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應碼 

Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //獲取響應內容 


} catch (UnsupportedEncodingException e) { 

e.printStackTrace(); 

} catch (ClientProtocolException e) { 

e.printStackTrace(); 

} catch (IOException e) { 

e.printStackTrace(); 


源信息來源 :http://blog.sina.com.cn/s/blog_71e00b880101gcws.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章