HttpClient之GET、POSTjava
Apache的httpComponents 項目是專一於http協議的的java組件。原生的URLConnection和server通訊,表單和文件傳送支持很差。因而就有了新的HttpClient,而且在新的httpclient裏面加入了以NIO爲基礎實現的非阻塞的I/O實現。本章內容只設計經常使用的get、post通訊。服務器
http請求包括內容: 請求行、請求頭、請求體:網絡
http響應包括內容:響應行、響應頭、響應體:dom
tips:詳細的http協議,請你們自行百度。這裏使用的IE9來訪問是http://www.sina.com.cn/展現異步
1.3 組成模塊
async
以4.5.1 發佈版爲準:post
a)httpComponents coreui
HttpCore 是一組基礎的http通訊組件,能在客服端和服務器之間傳送數據。支持:I/O模塊:阻塞I/O和非阻塞I/O(以JAVA的NIO爲基礎)。google
b)httpComponents clienturl
HttpClient是一個在httpcore的基礎實現的以http/1.1 協議設置的http代理。提供了可重複利用的組件:客服端身份驗證、地址管理、http鏈接管理。HttpComponents Client代替了HttpClient 3.x的的使用,建議用戶都升級。
c)httpComponents asynclient
異步HttpClient是以NIO和httpClient爲基礎並聽從http/1.1協議的代理。在那些須要大量鏈接、重要數據經過的使用,有很好的表現。
這個模版是官方提供,全部的Httpclient實現方式都是這樣開始 public void FunctionTemplate() throws ClientProtocolException, IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); //固定開始 //請求方式處理:請求類型(get/post),uri,請求頭、參數類型和數據(請求體) //HttpGet httpget = new HttpGet("http://localhost/"); HttpPost httpget = new HttpPost("http://localhost/"); //響應處理:響應行 CloseableHttpResponse response = httpclient.execute(httpget); try { // 響應數據處理 } catch (Exception e) { // TODO: handle exception } finally { response.close(); } }
1.get的參數傳遞能夠在uri中 //uri處理 public void TestUrl() throws URISyntaxException { // get--url:"http://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search&aq=f&oq=" // 方法一:貼全鏈接 // HttpGet httpGet = new // HttpGet("http://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search&aq=f&oq="); // 方法二:經過URI來組裝 URI uri = new URIBuilder().setScheme("http")// 協議 .setHost("www.google.com")// 主機 .setPath("/search")// 路徑 .setParameter("q", "httpclient")// ?後面的參數 .setParameter("btnG", "Google Search")// ?後面的參數 .setParameter("aq", "f")// ?後面的參數 .setParameter("oq", "")// ?後面的參數 .build(); HttpGet httpGet = new HttpGet(uri); } //處理請求頭 public void requestHeader() throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault();// 建立httpclient // 請求處理(主要是本身生成的請求頭和請求體) HttpGet httpget = new HttpGet("http://localhost/"); // 請求頭 Header header = new BasicHeader("Accpet-Encoiding", "gzip, deflate, sdch"); httpget.setHeader(header); CloseableHttpResponse response = null; try { response = httpclient.execute(httpget);// 響應處理 // 數據處理 } catch (Exception e) { // TODO: handle exception } finally { response.close(); } }
1.post發送數據須要用到HttpClient接口的總結 //傳送文件 public void fileEntity() throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault();// 建立httpclient // 請求處理(主要是本身生成的請求頭和請求體) HttpPost httpPost = new HttpPost("http://localhost/"); // 請求頭 Header header = new BasicHeader("Accpet-Encoiding", "gzip, deflate, sdch"); httpPost.setHeader(header); // 文件 File file = new File("test.txt"); FileEntity entity = new FileEntity(file, ContentType.create("text/plain", "UTF-8")); httpPost.setEntity(entity); CloseableHttpResponse response = null; try { response = httpclient.execute(httpPost);// 響應處理 // 數據處理 } catch (Exception e) { // TODO: handle exception } finally { response.close(); } } //傳送form數據 public void formEntity() throws IOException { // 建立httpclient CloseableHttpClient httpclient = HttpClients.createDefault(); // 請求處理(主要是本身生成的請求頭和請求體) HttpPost httpPost = new HttpPost("http://localhost/"); // 表單 List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("param1", "value1")); formparams.add(new BasicNameValuePair("param2", "value2")); // 格式化成 param1=value¶m2=value2 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams); // 當請求數據大小不定的時候能夠設置chunk爲true entity.setChunked(true); httpPost.setEntity(entity); CloseableHttpResponse response = null; try { // 響應處理 response = httpclient.execute(httpPost); // 數據處理 } catch (Exception e) { // TODO: handle exception } finally { response.close(); } }
public void testResponseEntity() { CloseableHttpClient httpclient = HttpClients.createDefault(); // 全部的網絡傳送須要網絡協議 HttpGet httpget = new HttpGet("http://www.baidu.com"); CloseableHttpResponse response = null; try { response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println(entity.getContentType()); // 利用inputstream-->BufferedReader---->string InputStream instream = entity.getContent(); try { String temp = null; BufferedReader r = new BufferedReader(new InputStreamReader(instream)); while ((temp = r.readLine()) != null) { System.out.println(temp); } } catch (Exception e) { } finally { instream.close(); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } finally { response = null; } } }
//1.響應行設置,就是 public void TestResponse() { // 響應行參數:Http/1.1 200 ok HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); System.out.println(response.getProtocolVersion());// 協議 System.out.println(response.getStatusLine().getStatusCode()); System.out.println(response.getStatusLine().getReasonPhrase()); System.out.println(response.getStatusLine().toString()); } //2.頭數據處理:key-value(請求/響應是經過h) public void TestHeader() { // 響應頭 HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); // 響應頭 response.addHeader("Set-Cookie", "c1=a; path=/; domain=localhost"); response.addHeader("Set-Cookie", "c2=a; path=\"/\"; domain=\"localhost\""); // 迭代 HeaderIterator it = response.headerIterator("Set-Cookie"); while (it.hasNext()) { System.out.println(it.next()); } } //3. Entity數據處理: public void TestEntity() throws ParseException, IOException { // 這裏是stirng類型 // content:important message 傳送的數據 // ContentType:數據類型 StringEntity myEntity = new StringEntity("important message", ContentType.create("text/plain", "UTF-8")); System.out.println(myEntity.getContentType()); System.out.println(myEntity.getContentLength()); System.out.println(myEntity.getContent()); System.out.println(EntityUtils.toString(myEntity)); System.out.println(EntityUtils.toByteArray(myEntity).length); }
a)HttpMessage接口:HttpGet、HttpPost:
b)Header接口:實現請求和響應頭數據設置(key-value)
b)HttpEntity接口:實現響應體和請求體。原理都是同樣在模型上都是用了策略模式。