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. 【9602】&&【b402】合并果子

    Time Limit: 1 second Memory Limit: 50 MB [问题描述] 在一个果园里,多多已经将所有的果子打了下来,而且按果子的不同种类分成了不同的堆.多多决定把所有的果子合成 ...

  2. Cocos2d-x V3.2+Cocos Studio1.6 实现一个简单的uibutton点击功能

    好久没写博客了 这几天在学习cocos studio,这个软件可以很方便的设计游戏的一些界面,并导入到cocos2dx中,今天就用button来做个样例 首先我们打开Cocos Studio1.6,选 ...

  3. jdk8-collect

    toMap 常用方式 public Map<Long, String> getIdNameMap(List<Account> accounts) { return accoun ...

  4. 【codeforces 782C】Andryusha and Colored Balloons

    [题目链接]:http://codeforces.com/contest/782/problem/C [题意] 给你一棵树 让你满足要求 ->任意相连的3个节点的颜色不能相同 的情况下进行染色 ...

  5. Unity3d报告奇怪的错误CompareBaseObjectsInternal can only be called from the main thread.

    其中使用了该项目.NET的Async Socket代码.后来不知道什么时候这个奇怪的错误的出现: CompareBaseObjectsInternal can only be called from ...

  6. ubuntu12.04下编译安装x86平台qt库qt-everywhere-opensource-src-4.8.5

    本文记录PC(x86)下安装Linux/X11版Qt 开发环境.下载页面:http://qt-project.org/downloads ARM嵌入式版本qt库的编译安装详见<unbunt12. ...

  7. Leetcode 169 Majority Element 分治

    在一个长度为n的数组中找出出现次数超过(n+1)/2次的数 说明请参考编程之美中的2.3 class Solution { public: int majorityElement(vector< ...

  8. ISO/IEC 27001 信息安全管理体系认证

    一. 信息安全管理体系标准业务介绍 1. 背景介绍 信息作为组织的重要资产,需要得到妥善保护.但随着信息技术的高速发展,特别是Internet的问世及网上交易的启用,许多信息安全的问题也纷纷出现:系统 ...

  9. 受限玻尔兹曼机(RBM)以及对比散度(CD)

    1. RBM 的提出 BM 的缺点: 计算时间漫长,尤其是无约束自由迭代的负向阶段: 对抽样噪音敏感: 流行软件的不支持: 受限玻尔兹曼机(Restricted Boltzmann Machine,简 ...

  10. 转义及编码(\u, \x)

    首先前面的 \表示转义, \x:只是 16 进制的意思,后边跟两位,则表示单字节编码: \d:十进制:\o:八进制: 对于 \xaa ⇒ chr(0xaa) ⇒ chr(16*a+a) \u:unic ...