java 實現HTTP串連(HTTPClient)

來源:互聯網
上載者:User

標籤:value   通用   int   整理   nbsp   for   列印   http   add   

  在實習中,使用到了http串連,一直理解的很模糊,特地寫個分析整理篇。分析不到位的地方請多多指教。

  Http 目前通用版本為 http 1.1 。

  Http串連大致分為2種常用的請求——GET,POST

  一.基本流程(使用httpClient)

  GET{

  1.建立HttpClient 對象 ——HttpClient http = HttpClients.createDefault();

  2.建立GET 請求——HttpGet get = new HttpGet(url——介面地址/請求路徑);

  3.擷取響應——HttpResponse resp = http.execute(get);

  4.擷取響應實體 —— HttpEntity entity = resp.getEntity();

  5.建立結果對象String ——String result = EntityUtils.toString(entity,"utf-8");

  6.列印——System.out.print("結果是:"+result);

  }

 

  POST{

  1.建立HttpClient 對象 ——HttpClient http = HttpClients.createDefault();

  2.建立POST請求——HttpPost post = new HttpPost(url——介面地址/請求路徑);

  3.建立一個List容器,存放基本的索引值對——{

                      List<BasicNameValuePair> params = new ArrayLIst<>(); 

                      params.add(索引值對1);

                      params.add(索引值對2);

                      }

  4.在請求中添加訊息實體——post.setEntity(new UrlEncodedFormEntity(params,"utf-8"));

  5.擷取響應——HttpResponse resp = http.execute(post);

  6.擷取響應實體—— HttpEntity entity = resp.getEntity();

  7.建立結果對象——String result = EntityUtils.toString(entity,"utf-8");

  8.列印——System.out.print("結果是:"+result);

  }

 

暫時是這麼一回事。

 

java 實現HTTP串連(HTTPClient)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.