HttpClient發送json、普通參數類型的Post請求


前言:
  當傳遞json參數時,需要使用StringEntity將Content-Type設置為text/plain類型
  當傳遞非json參數,正常的表單數據時,使用
UrlEncodedFormEntity將Content-Type設置為application/x-www-form-urlencoded類型

1、Post請求傳json數據

   // 省略前面聲明請求、設置Header等操作,直接從傳遞參數開始
   JSONObject json = new JSONObject();
   json.put("filePath","js");
   json.put("projectId","61020ccdfd33d86b6abe8745");
   json.put("type","fileFolder");
      
   // 將參數放到Post中
   // 通過new StringEntity(),可將Content-Type設置為text/plain類型
   httpPost.setEntity(new StringEntity(json.toString(),"UTF-8"));

2、Post請求傳普通參數 

   JSONObject json = new JSONObject();
   json.put("filePath","js");
   json.put("projectId","61020ccdfd33d86b6abe8745");
   json.put("type","fileFolder");
    // 設置參數
   List<NameValuePair> parameters = new ArrayList<NameValuePair>();
   for(String key:json.keySet()) {
     parameters.add(new BasicNameValuePair(key, json.getString(key)));
   }
 
   // 將Content-Type設置為application/x-www-form-urlencoded類型
   UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
   httpPost.setEntity(formEntity); 

3、maven依賴

<dependency>
  <groupId>commons-httpclient</groupId>
  <artifactId>commons-httpclient</artifactId>
  <version>3.1</version>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.76</version>
</dependency>

 


完整代碼:


import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yc
 * @Description:
 * @Date: 2021/07/27/18:32
 */
public class HttpClientUtil {

    public static String url = "http://192.168.9.27:3080/co/cmd/deleteProject";

    public static String deletePost() throws IOException {
        String string = "";

        // 獲取HttpClient對象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 聲明post請求
        HttpPost httpPost = new HttpPost(url);

        // 設置請求頭,在post請求中限制了瀏覽器才能訪問
        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36");
        httpPost.addHeader("Accept", "*/*");
        httpPost.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpPost.addHeader("Content-Type", "application/json");
//        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
        httpPost.addHeader("Connection", "keep-alive");
        // 設置token
        httpPost.addHeader("Authorization","eyJ0eXAiOiJKV1QiLCJhbGciOiJIDASDUzI1NiJ9.eyJleHAiOjE2Mjc0NTQzODYsInVzZXJuYW1lIjoiYWJjZCJ9.MYvNg03txeNm_KiI27fdS0KViVxWhLntDjBjiP44UYQDASCSACCSA");

     JSONObject json = new JSONObject();
     json.put("filePath","js");
     json.put("projectId","61020ccdfd33d86b6abe8745");
     json.put("type","fileFolder");
     
// Post請求發送json類型數據,將Content-Type設置為text/plain類型 httpPost.setEntity(new StringEntity(json.toString(),"UTF-8"));      // 設置參數(Post請求發送非json數據類型) //List<NameValuePair> parameters = new ArrayList<NameValuePair>(); //for(String key:json.keySet()) { // parameters.add(new BasicNameValuePair(key, json.getString(key))); //}      // 將Content-Type設置為application/x-www-form-urlencoded類型 //UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8"); //httpPost.setEntity(formEntity); // 發送請求 CloseableHttpResponse response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); string = EntityUtils.toString(entity, "utf-8"); } else { string = "操作失敗"; return string; } // 關閉資源 response.close(); httpClient.close(); return string; } }
 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM