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数据的更多相关文章

  1. java模拟post请求发送json

    java模拟post请求发送json,用两种方式实现,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求, 方法一: package main ...

  2. Java模拟POST请求发送二进制数据

    在进行程序之间数据通信时我们有时候就需要自定义二进制格式,然后通过HTTP进行二进制数据交互.交互的示例代码如下: public static void main(String[] args) { S ...

  3. Http请求发送json数据用实体类接收

    以上是请求URL以及json数据 接收层

  4. java使用httpcomponents post发送json数据

    一.适用场景 当我们向第三方系统提交数据的时候,需要调用第三方系统提供的接口.不同的系统提供的接口也不一样,有的是SOAP Webservice.RESTful Webservice 或其他的.当使用 ...

  5. java Http post请求发送json字符串

    最近差点被业务逻辑搞懵逼,果然要先花时间思考,确定好流程再执行.目前最好用的jar包还是org.apache.http. public class HttpClientHelper { private ...

  6. jmeter ---模拟http请求/发送gzip数据

    jmeter中get请求gzip数据的方法: 在jmeter线程组中添加“http信息头管理器”,并添加名称:Accept-Encoding值: gzip,deflate注:HTTP信息头Accept ...

  7. C# 后台模拟前台post发送json数据

    public static string PostMoths(string url, string param) { string strURL = url; System.Net.HttpWebRe ...

  8. python 全栈开发,Day75(Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件)

    昨日内容回顾 基于对象的跨表查询 正向查询:关联属性在A表中,所以A对象找关联B表数据,正向查询 反向查询:关联属性在A表中,所以B对象找A对象,反向查询 一对多: 按字段:xx book ----- ...

  9. Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件

    一.Django与Ajax AJAX准备知识:JSON 什么是 JSON ? JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation) JSON 是轻 ...

随机推荐

  1. (ubuntu 下)tensorflow 的安装及版本升级

    对于 CPU 版本 pip3 install –upgrade tensorflow 对于 GPU 版本: pip3 install –upgrade tensorflow-gpu [TensorFl ...

  2. KVC设置系统自带属性,不管是不是私有的属性

    KVC   可以设置系统自带属性,不管是不是私有的属性:    1,   2,  

  3. NOIP模拟 MST - 类次小生成树

    题目大意: 给一张无向图,可以将图中权值为v的边修改为k-v,求修改后的最小生成树边权和. 题目分析: 最小生成树的环切定理:任何非树边一定比对应树链上的所有边权值要大.否则我们可以将链上最大的树边删 ...

  4. 【50.49%】【codeforces 731B】Coupons and Discounts

    time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...

  5. Nginx得知——流程模型(worker流程)

    流程模型 worker流程 master进程模型核心函数ngx_master_process_cycle()中调用了创建子进程函数ngx_start_worker_processes(),该函数源代码 ...

  6. Material Design: NavigationView FlaotingActionBar SnackBar采用

    转载 请明确说明 MingsangAndroid 本文介绍了Design Support Library的引入 拥抱Android Design Support Library新变化(导航视图.悬浮A ...

  7. Managing uniquely tagged items using the internet

    The invention teaches managing an item in the Internet of Things, wherein the system comprises: an i ...

  8. 初探js

    第一章   1.JS的位置 1-1.行间 1-2.内嵌 1-3.外联 2.JS的标签位置 页面中的代码在一般情况下会按从上到下的顺序,从左往右的顺序执行. 因此当JS放在了元素上面的时候,就不能正常执 ...

  9. MySQL - 常见的三种数据库存储引擎

    原文:MySQL - 常见的三种数据库存储引擎 数据库存储引擎:是数据库底层软件组织,数据库管理系统(DBMS)使用数据引擎进行创建.查询.更新和删除数据.不同的存储引擎提供不同的存储机制.索引技巧. ...

  10. 它们的定义Activity跳转动画

    本来觉得是一个非常小的需求, 后来我发现总是 错误, 采用Theme于 4.0在 操作不是很容易使用. 后来查阅资料, 须要在finish 后面 和 startActivity 后面加入 overri ...