1. 程式人生 > 其它 >HttpClient傳送json/其他引數型別的請求

HttpClient傳送json/其他引數型別的請求

HttpClientUtil類


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.8.247:3000/co/cmd/deleteProjectCmd";
public static String username = "";
public static String password = "";


public static String projectTreeDeletePost(JSONObject json) throws IOException {
String string = "";
// 1.獲取HttpClient物件
CloseableHttpClient httpClient = HttpClients.createDefault();

// 2.宣告post請求
HttpPost httpPost = new HttpPost(url);
// 3.設定請求頭,為了安全,防止惡意攻擊,在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","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2Mjc0NTQzODYsInVzZXJuYW1lIjoiYWJjZCJ9.MYvNg03txeNm_KiI27fdS0KViVxWhLntDjBjiP44UYQ");
// 4.設定引數
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
for(String key:json.keySet()) {
parameters.add(new BasicNameValuePair(key, json.getString(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
httpPost.setEntity(formEntity);
// json引數
//httpPost.setEntity(new StringEntity(json.toString()));

// 5.傳送請求
CloseableHttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
string = EntityUtils.toString(entity, "utf-8");
}
else
{
string = "操作失敗";
return string;
}
// 7.關閉資源
response.close();
httpClient.close();
return string;
}
}