Java如何实现post请求--并传送json字符串呢?
下文笔者讲述java代码实现post请求---并发送json字符串的方法分享,如下所示
实现思路:
借助HttpClient中的RequestEntity对象
并将json字符串放入到请求体中,发送url请求体中接口
例
//引入jar包
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
//编写发送json字符串的util类
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param jsonData
* 请求参数,请求参数应该是Json格式字符串的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendJsonPost(String url, String jsonData) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
HttpClient client = new HttpClient(); // 客户端实例化
PostMethod postMethod = new PostMethod(url); // 请求方法post,可以将请求路径传入构造参数中
postMethod.addRequestHeader("Content-type", "application/json; charset=utf-8");
//postMethod.addRequestHeader("Authorization", "ey**");
byte[] requestBytes = jsonData.getBytes("utf-8"); // 将参数转为二进制流
InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,requestBytes.length);
// 请求体
RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,requestBytes.length,
"application/json; charset=utf-8");
postMethod.setRequestEntity(requestEntity); // 将参数放入请求体
int i = client.executeMethod(postMethod); // 执行方法
System.out.println("请求状态"+i);
byte[] responseBody = postMethod.getResponseBody(); // 得到相应数据
String s = new String(responseBody);
System.out.println(s);
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


