java模拟post请求发送json数据
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>
java模拟post请求发送json数据的更多相关文章
- java模拟post请求发送json
java模拟post请求发送json,用两种方式实现,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求, 方法一: package main ...
- Java模拟POST请求发送二进制数据
在进行程序之间数据通信时我们有时候就需要自定义二进制格式,然后通过HTTP进行二进制数据交互.交互的示例代码如下: public static void main(String[] args) { S ...
- Http请求发送json数据用实体类接收
以上是请求URL以及json数据 接收层
- java使用httpcomponents post发送json数据
一.适用场景 当我们向第三方系统提交数据的时候,需要调用第三方系统提供的接口.不同的系统提供的接口也不一样,有的是SOAP Webservice.RESTful Webservice 或其他的.当使用 ...
- java Http post请求发送json字符串
最近差点被业务逻辑搞懵逼,果然要先花时间思考,确定好流程再执行.目前最好用的jar包还是org.apache.http. public class HttpClientHelper { private ...
- jmeter ---模拟http请求/发送gzip数据
jmeter中get请求gzip数据的方法: 在jmeter线程组中添加“http信息头管理器”,并添加名称:Accept-Encoding值: gzip,deflate注:HTTP信息头Accept ...
- C# 后台模拟前台post发送json数据
public static string PostMoths(string url, string param) { string strURL = url; System.Net.HttpWebRe ...
- python 全栈开发,Day75(Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件)
昨日内容回顾 基于对象的跨表查询 正向查询:关联属性在A表中,所以A对象找关联B表数据,正向查询 反向查询:关联属性在A表中,所以B对象找A对象,反向查询 一对多: 按字段:xx book ----- ...
- Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件
一.Django与Ajax AJAX准备知识:JSON 什么是 JSON ? JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation) JSON 是轻 ...
随机推荐
- gdal以GA_Update方式打开jpg文件的做法
作者:朱金灿 来源:http://blog.csdn.net/clever101 gdal库是不支持以GA_Update方式打开jpg文件的,原因在于gdal_1_10_1\frmts\jpeg文件夹 ...
- 【BZOJ 1036】[ZJOI2008]树的统计Count
[题目链接]:http://www.lydsy.com/JudgeOnline/problem.php?id=1036 [题意] [题解] 树链剖分入门题; 每一条链维护一个线段树就好; uppest ...
- 使用Akka、Kafka和ElasticSearch等构建分析引擎 -- good
本文翻译自Building Analytics Engine Using Akka, Kafka & ElasticSearch,已获得原作者Satendra Kumar和网站授权. 在这篇文 ...
- HDU 4847-Wow! Such Doge!(定位)
Wow! Such Doge! Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) ...
- c语言学习笔记(5)——进制
进制 1.什么叫进制? 逢n进1: 2.把r进制转成十进制 a*r^0+b*r^1+c*r^2..... 3.把十进制转成r进制 185----->(r进制) 185不停的除r取余,最后把余数 ...
- Android系统联系人全特效实现(上),分组导航和挤压动画
记得在我刚接触Android的时候对系统联系人中的特效很感兴趣,它会根据手机中联系人姓氏的首字母进行分组,并在界面的最顶端始终显示一个当前的分组.如下图所示: 最让我感兴趣的是,当后一个分组和前一个分 ...
- 在.net core项目中想使用类似iis上面虚拟目录的功能
事实上iis是不支持.net core mvc项目虚拟目录的.你在iis上发布网站 然后在wwwroot目录上创建虚拟目录,指向硬盘其他位置上的文件夹,是不会有效果的. 正确的处理方式应该是修改静态文 ...
- .net core下,Ocelot网关与Spring Cloud Gateway网关的对比测试
有感于 myzony 发布的 针对 Ocelot 网关的性能测试 ,并且公司下一步也需要对.net和java的应用做一定的整合,于是对Ocelot网关.Spring Cloud Gateway网关做个 ...
- 简明Python3教程 首页
A Byte of Python 'A Byte of Python' is a free book on programming using the Python language. It serv ...
- phpstorm 删除空行
思路: 用正则把所有空行找到,然后一键全部替换. 步骤:首先把 Regex 打上勾ctrl+f 搜索框就填写正则规则:^\nctrl+r 匹配到所有空行之后,点击[Replace all]即可