JAVA发送POST请求携带JSON格式字符串参数

时间:2022-09-15 17:24:06
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; public class PostUtil { /**
* 发送post请求
* @param url 请求地址
* @param json json格式字符串
* @param contentType 这里用 "application/json"
* @return
*/
public static String post(String url, String json, String contentType) {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
//HttpClient
CloseableHttpClient client = httpClientBuilder.build();
client = (CloseableHttpClient) wrapClient(client);
HttpPost post = new HttpPost(url);
try {
StringEntity s = new StringEntity(json, "utf-8");
if (StringUtils.isBlank(contentType)) {
s.setContentType("application/json");
}
s.setContentType(contentType);
post.setEntity(s);
HttpResponse res = client.execute(post);
HttpEntity entity = res.getEntity();
String str = EntityUtils.toString(entity, "utf-8");
return str;
} catch (Exception e) {
e.printStackTrace();
}
return null;
} private static org.apache.http.client.HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLSv1");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
} public void checkServerTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
} public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx, new String[]{"TLSv1"}, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpclient; } catch (Exception ex) {
return null;
}
} public class CharsetHandler implements ResponseHandler<String> {
private String charset; public CharsetHandler(String charset) {
this.charset = charset;
} public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity != null) {
if (!StringUtils.isBlank(charset)) {
return EntityUtils.toString(entity, charset);
} else {
return EntityUtils.toString(entity);
}
} else {
return null;
}
}
} }

JAVA发送POST请求携带JSON格式字符串参数的更多相关文章

  1. SpringMVC中使用Ajax POST请求以json格式传递参数服务端通过request&period;getParameter&lpar;&quot&semi;name&quot&semi;&rpar;无法获取参数值问题分析

    SpringMVC中使用Ajax POST请求以json格式传递参数服务端通过request.getParameter("name")无法获取参数值问题分析 一:问题demo展示 ...

  2. 发送Ajax请求获取JSON格式数据

    Aspx前端页面: <script type="text/javascript"> $(function () { $.getJSON("Ajax/TestA ...

  3. Jmeter请求非Json格式的参数如何添加

    Step1: 可以先在用户自定义变量中加入你需要添加的请求类型,具体参考图片 Step2: 在线程组下请求之前添加HTTP信息头管理器

  4. Java 发送 Https 请求工具类 (兼容http)

    依赖 jsoup-1.11.3.jar <dependency> <groupId>org.jsoup</groupId> <artifactId>js ...

  5. JSON&lpar;五)——同步请求中使用JSON格式字符串进行交互(不太常见的用法)

    在同步请求中使用JSON格式进行数据交互的场景并不多,同步请求是浏览器直接与服务器进行数据交互的大多是用jsp的标签jstl和el表达式对请求中的数据进行数据的渲染.我也是在一次开发中要从其它服务器提 ...

  6. json格式字符串与java&period;util&period;Map的互转&lpar;借助于jackson&period;jar&rpar;

    package com.test.javaAPI.json; /** * json工具类 * * @author Wei * @time 2016年10月2日 下午4:25:25 */ public ...

  7. JSon&lowbar;零基础&lowbar;001&lowbar;将布尔类型数组转换为JSon格式字符串,返回给界面

    将布尔类型数组转换为JSon格式字符串,返回给界面 需要导入包: 编写bean: package com.west.webcourse.po; /** * 第01步:编写bean类, * 下一步com ...

  8. Java发送Http请求并获取状态码

    通过Java发送url请求,查看该url是否有效,这时我们可以通过获取状态码来判断. try { URL u = new URL("http://10.1.2.8:8080/fqz/page ...

  9. play framework接收post请求json格式的参数

    大家在用play framework框架开发第三方调用你的接口的时候并且用json格式的参数post请求 ,参数接收是个问题 ,因为play对表单提交post请求有处理: 有两种方法: 1.直接形参列 ...

随机推荐

  1. iterm2配色

    #enables colorin the terminal bash shell export export CLICOLOR= #sets up thecolor scheme for list e ...

  2. js判断图片是否存在&comma;并做处理

    <html> <head> <meta http-equiv="Content-Type" content="text/html; char ...

  3. ReportViewer中设置ServerReport&period;ReportServerCredentials属性的方法

    当使用SSRS技术来布置报表,可能使用MS自带的ReportViewer控件来读取报表. 它分为Web和Windows两种版本;此处Web版. ServerReport.ReportServerCre ...

  4. 前端project师,确定你的目标吧!无能的人才管他叫命运

    导语: 你为自己定过一个不靠谱的目标,是20年前的事了吧. 长大你想干什么?你的回答是什么?现在实现了吗? 如今,你每天都坐在同一个格子间的同一个电脑前,会不会感到每天都像是在复印,感到前途是模糊的, ...

  5. JQuery操作DOM对象

    1.追加节点( 儿子关系) append()     $("已有元素").append("动态添加元素");  在已有元素的内部的后面追加一个元素 append ...

  6. ECJTUACM16 Winter vacation training &num;1 题解&amp&semi;源码

    //寒假训练赛,第一次拿第一,感觉很爽哦,AC3题! A------------------------------------------------------------------------ ...

  7. python笔记之序列

    str字符串 表达:单引号,双引号,反斜杠 'let\'s go.' #只使用单引号,外部使用单引号,内部单引号用反斜杠 "let's go. " #单双引号混合使用 长字符串 使 ...

  8. python从FTP下载文件

    #!/usr/bin/python # -*- coding: utf-8 -*- """ FTP常用操作 """ from ftplib ...

  9. Grep console 设置

    Grep console     DEBUG 9961B8 INFO 4B5E76 WARN 8A8A00 ERROR 9F6B00 8A7674      

  10. MySQL 基础回顾

    mysql 回顾 数据库的设计必须满足三范式 1NF: 强调列的原子性,列不可拆分 eg: 一张表(联系人) 有(姓名,性别,电话)三列,但是现实中电话又可分为家庭电话和公司电话,这种表结构设计就不符 ...