import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* HTTP工具
*
* @author 洛天依
*/
public class HttpUtil {
// url连接 body json参数
public static String sendHttpPost(String url, JSONObject body) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
//装填参数
StringEntity s = new StringEntity(body.toString(), "utf-8");
//设置参数到请求对象中
httpPost.setEntity(s);
// 设置头
httpPost.addHeader("Cookie", "gid_87f036f882014cd8=d36851103c8a9b4210732f978b24273aee6c9c3e; ls_371ef9f55b6b63dc=2bc29f8964484170");
httpPost.addHeader("Content-type", "application/json;chartset=UTF-8");
httpPost.addHeader("User-Agent", "PostmanRuntime/7.26.2");
httpPost.addHeader("Accept", "*/*");
httpPost.addHeader("Accept-Encoding", "gzip, deflate, br");
httpPost.addHeader("Connection", "keep-alive");
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, "UTF-8");
response.close();
httpClient.close();
return responseContent;
}
}
java代码模拟postman请求头发送POST
最新推荐文章于 2024-02-28 10:46:41 发布