java模拟post请求发送json数据

时间:2022-02-23 15:36:16
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
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;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL; public class HttpRequest2 {
public static String sendPost(String url,String param){
OutputStreamWriter out =null;
BufferedReader reader = null;
String response = ""; //创建连接
try {
URL httpUrl = null; //HTTP URL类 用这个类来创建连接
//创建URL
httpUrl = new URL(url);
//建立连接
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("connection", "keep-alive");
conn.setUseCaches(false);//设置不要缓存
conn.setInstanceFollowRedirects(true);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
//POST请求
out = new OutputStreamWriter(
conn.getOutputStream());
out.write(param);
out.flush();
//读取响应
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String lines;
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
response+=lines;
}
reader.close();
// 断开连接
conn.disconnect(); } catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(reader!=null){
reader.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
} return response;
} public static String sendPost2(String url, String data) {
String response = null; try {
CloseableHttpClient httpclient = null;
CloseableHttpResponse httpresponse = null;
try {
httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
StringEntity stringentity = new StringEntity(data,
ContentType.create("text/json", "UTF-8"));
httppost.setEntity(stringentity);
httpresponse = httpclient.execute(httppost);
response = EntityUtils
.toString(httpresponse.getEntity()); } finally {
if (httpclient != null) {
httpclient.close();
}
if (httpresponse != null) {
httpresponse.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
} public static void main(String[] args) {
JSONObject jsonParam = new JSONObject();
jsonParam.put("id", "");
jsonParam.put("name", "zhangsan");
String param = jsonParam.toJSONString(); String url="http://localhost:8080/demo/one"; String sendPost = sendPost2(url, param);
System.out.println(sendPost); } }

下面是后台的代码

@RestController
@RequestMapping("/demo")
public class PostController { @Resource
protected HttpServletRequest request; @RequestMapping(value = "/one",method = RequestMethod.POST)
public String getResult(String str)throws Exception{ InputStreamReader reader = new InputStreamReader(request.getInputStream(),"UTF-8");
char[] buff = new char[];
int length =;
while((length =reader.read(buff))!=-){
String message = new String(buff,,length);
System.out.println("接收到的信息 "+ message);
} return JSON.toJSONString("这是post请求");
}
}

依赖的jar包

 <!--http 请求需要的jar包-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>