安卓如何訪問云服務(wù)器地址?使用安卓程序連接到云服務(wù)器,用httpClient或者okhttp 原理都是一樣,發(fā)起http請求傳遞數(shù)據(jù),解析結(jié)果。這里我們根據(jù)百度知道網(wǎng)友的介紹,舉例一下 httpClient 的用法:
1. GET 方式傳遞參數(shù)
//先將參數(shù)放入List,再對參數(shù)進行URL編碼
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair(“param1”, “數(shù)據(jù)”)); // 增加參數(shù)1
params.add(new BasicNameValuePair(“param2”, “value2”));// 增加參數(shù)2
String param = URLEncodedUtils.format(params, “UTF-8”);// 對參數(shù)編碼
String baseUrl = “服務(wù)器接口完整URL”;
HttpGet getMethod = new HttpGet(baseUrl + “?” + param);// 將URL與參數(shù)拼接
HttpClient httpClient = new DefaultHttpClient();
try {HttpResponse response = httpClient.execute(getMethod); // 發(fā)起GET請求
Log.i(TAG, “resCode = ” + response.getStatusLine().getStatusCode()); // 獲取響應碼
Log.i(TAG, “result = ” + EntityUtils.toString(response.getEntity(), “utf-8”));// 獲取服務(wù)器響應內(nèi)容
} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e)
{e.printStackTrace();}
2. POST方式 方式傳遞參數(shù)
//和GET方式一樣,先將參數(shù)放入List
params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair(“param1”, “Post方法”));// 增加參數(shù)1
params.add(new BasicNameValuePair(“param2”, “第二個參數(shù)”));// 增加參數(shù)2
try {HttpPost postMethod = new HttpPost(baseUrl);// 創(chuàng)建一個post請求
postMethod.setEntity(new UrlEncodedFormEntity(params, “utf-8”)); // 將參數(shù)填入POST Entity中
HttpResponse response = httpClient.execute(postMethod); //執(zhí)行POST方法
Log.i(TAG, “resCode = ” + response.getStatusLine().getStatusCode()); // 獲取響應碼
Log.i(TAG, “result = ” + EntityUtils.toString(response.getEntity(), “utf-8”)); // 獲取響應內(nèi)容
} catch (UnsupportedEncodingException e) {e.printStackTrace();
} catch (ClientProtocolException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
以上是關(guān)于安卓如何訪問云服務(wù)器地址的分享,域名頻道網(wǎng)站提供多類型、高性價的云服務(wù)器產(chǎn)品,云主機購買鏈接 http://fascinatingdeals.com/vps/