HttpURLConnection的經常使用方法服務器
// 獲取連接網絡的路徑網絡
URL url = new URL(strUrl);post
// 準備開啓網絡.設置訪問網絡的配置url
HttpURLConnection httpURLConnection = (HttpURLConnection) url .openConnection(); httpURLConnection.setConnectTimeout(1000); httpURLConnection.setReadTimeout(1000);spa
httpURLConnection.connect();code
// 獲取響應值 int lin = httpURLConnection.getResponseCode();orm
// 判斷返回值是否爲200對象
if (lin == 200) {utf-8
// 若是知足條件開始讀取信息字符串
// 準備
InputStream inputStream = httpURLConnection.getInputStream();
byte[] bt = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// 開始讀取內容
int leng = -1;
while ((leng = inputStream.read(bt)) != -1) {
byteArrayOutputStream.write(bt, 0, leng);
}
// 關閉流 inputStream.close();
// 轉換成string字符串 String string = byteArrayOutputStream.toString();
HttpGet的聯網方式
//獲得httplient對象 HttpClient httpClient = new DefaultHttpClient();
//使用get方式訪問網絡並指定路徑 HttpGet httpGet = new HttpGet(url);
//執行聯網操做,發送get請求 HttpResponse httpResponse = httpClient.execute(httpGet);
//判斷是否爲狀態碼(200)
HttpStatus.SC_PK == httpResponse.toStatusLine().getStatusCode();
//在while循環正,將服務器返回的實體轉出字符串
EntityUtils.toString(entity, 「utf-8」);
POST請求的網絡連接方式
//建立httpClient對象
HttpClient client = new DefaultHttpClient();
//建立http post請求對象,並指定路徑 HttpPost post = new HttpPost(url);
// 將要提交的數據以name--value的形式傳遞
BasicNameValuePair pair = new BasicNameValuePair("name", name);
//把要提交的數據以實體的形式設置到post對象中
List parameters = new ArrayList();
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8"); post.setEntity(entity);
//執行聯網操做,進行post請求
HttpResponse response = client.execute(post);
//獲取狀態行 StatusLine line = response.getStatusLine();
//獲取狀態碼(200)
int statusCode = line.getStatusCode();
//獲取實體對象,實體指的是服務器返回的數據
HttpEntity entity = response.getEntity();
//將服務器返回的實體轉出字符串 EntityUtils.toString(entity, "utf-8");
三種請求方式,註釋在代碼的上方