4-7 HTTP操作(一)
1 什麼是HTTP協議
超文本傳輸協議
客戶端和服務器端請求應答的標準
客戶端瀏覽器或其他程序與Web服務器之間的應用層通信協議
無狀態協議
2 HTTP工作原理
建立連接
客戶端發送請求
服務器端響應請求
斷開連接
3 HTTP運行流程
請求報文格式:
請求行-通用信息頭-請求頭-實體頭-報文主體
響應報文格式:
響應行-通用信息頭-響應頭-實體頭-報文主體
4-8 HTTP操作(二)
1 Apache HTTP API 介紹
2 發送請求和接受響應的流程
//生成一個請求對象
HttpGet httpGet = new HttpGet("http://www.baidu.com");
//生成一個Http客戶端對象
HttpClient httpClient = new DefaultHttpClient();
//使用Http客戶端發送請求對象
HttpResponse httpResponse = httpClient.execute(httpGet); //該方法會返回一個HttpResponse對象
//取出內容 代表一個Http消息
HttpEntity httpEntity = httpResponse.getEntity();
InputStream inputStream = httpEntity.getContent();
//進行一些IO流的操作
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String result = "";
String line = "";
while((line = reader.readLine()) = null){
result = result + line;
}
System.out.println(result);
//...
inputStream.close();
4-9 HTTP操作(三)
1 HTTP請求的方法
2 使用GET方法發送請求
get URL xxxxx?key=value&key=value...
剩下的操作和HTTP2中一樣
url爲拼上?key=value..之後的url
3 使用POST方法發送請求
NameValuePair nameValuePair1 = new BasicNameValuePair("name",name); //name爲讀取的值
NameValuePair nameValuePair2 = new BasicNameValuePair("age",age); //age爲讀取的值
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(nameValuePair1);
nameValuePairs.add(nameValuePair2);
//生成Entity對象
HttpEntity requestHttpEntity = new UrlEncodedFormEntity(nameValuePairs);
HttpPost httpPost = new HttpPost(url); //這裏的url是baseUrl 不用拼上?key=value...
httpPost.setEntity(requestEntity);
//之後的操作一樣