1. 程式人生 > 其它 >RestFul----httpclient呼叫例子-post

RestFul----httpclient呼叫例子-post

技術標籤:RestFuljava

一. 使用url傳遞引數的方式:

     List<NameValuePair> parameters4 = new ArrayList<NameValuePair>();
            parameters4.add(new BasicNameValuePair("data", json));
            HttpEntity entms4 = new UrlEncodedFormEntity(parameters4, "UTF-8");
            httppost.setEntity(entms4);

二. 使用body傳遞引數

   StringEntity s = new StringEntity(json.toString());
      httppost.setEntity(s);

三. 例子如下:

String url="http://192.168.87.149:8084/api/TokenAuth/GetToken";
  // 建立預設的httpClient例項.
   CloseableHttpClient httpclient = HttpClients.createDefault();

  CloseableHttpResponse response;
    try {
   HttpPost httppost = new HttpPost(url);
   JSONObject json = new JSONObject();
   json.put("userName", "******");
   json.put("password", "**********");
   
   StringEntity s = new StringEntity(json.toString());

   //HttpEntity entms4 = new UrlEncodedFormEntity(parameters4, "UTF-8");
   httppost.setEntity(s);
      httppost.setHeader("Accept", "application/json");
   httppost.setHeader("Content-Type", "application/json");
      response = httpclient.execute(httppost);
   
   StatusLine statusLine = response.getStatusLine();
   //確認傳送
   if (statusLine.getStatusCode() == HttpStatus.SC_OK) {//連結成功
   //通過HttpResponse介面的getEntity方法返回響應資訊,並進行相應的處理。
   String result = EntityUtils.toString(response.getEntity());
     
   } else {
   //傳送失敗時的處理
    System.out.println("失敗"+statusLine.getStatusCode());
   }

}finally {
      // 關閉連線,釋放資源
      try {
       httpclient.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }