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. JDBC连接数据库步骤及Class.forName()(转)

    JDBC连接数据库 JDBC是Sun公司制定的一个可以用Java语言连接数据库的技术. 一.JDBC基础知识 JDBC(Java DataBase Connectivity,java数据库连接)是一种 ...

  2. NOIP模拟 Math - 数学

    题目大意: 给定a,n(\(a \le 1e9, n\le30\)),求有多少\(b(1 \le b \le 2^n)\)满足:\(a^b \equiv b^a(mod 2^n)\). 题目分析: 数 ...

  3. ART、JIT、AOT、Dalvik之间有什么关系?

    JIT与Dalvik JIT是"Just In Time Compiler"的缩写,就是"即时编译技术",与Dalvik虚拟机相关. 怎么理解这句话呢?这要从A ...

  4. 基于webRTC技术 音频和视频,IM解

    由于原来的文章 http://blog.csdn.net/voipmaker  转载注明出处. 基于WebRTC技术可实现点对点音视频.即时通信.视频会议.最新的系统组件包含: TeleICE NAT ...

  5. Arcgis api for javascript学习笔记(4.5版本)-三维地图并叠加天地图标注

    1.三维地图实现 在官网的demo中就有三维地图的实现,如下图所示 <!DOCTYPE html> <html> <head> <meta charset=& ...

  6. Android 光标位置设置

    EditText edit =(EditText) findViewById(R.id.etTest); 1.设置光标在EditText中的指定位置 edit.setSelection(1); 需要注 ...

  7. node lesson2

    var express = require('express'); var utility = require('utility'); var app = express(); app.get('/' ...

  8. CUDA查询和选取设备信息

    CUDA查询设备信息 CUDA C中的cudaGetDeviceProperties函数可以很方便的获取到设备的信息,函数原型是: cudaError_t CUDARTAPI cudaGetDevic ...

  9. php+mysql+nginx于linux部署对环境

    始终linux在补锅匠,在尚未完成linux根据 - 型nginxserver环境进行部署,这些天来,无论它是什么部署,遇到的问题非常多,今天,我的环境中部署文档发行,够一起讨论一下,希望大家採用后遇 ...

  10. visualsvn server 提交修改日志

    修改日志时遇到以下错误: Repository has not been enabled to accept revision propchanges;ask the administrator to ...