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", "12306");
        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[1024];
        int length =0;
        while((length =reader.read(buff))!=-1){
            String message = new String(buff,0,length);
            System.out.println("接收到的信息   "+ message);
        }

        return JSON.toJSONString("这是post请求");
    }
}

原文地址:https://www.cnblogs.com/zhuguangzhe/p/10751459.html

时间: 2024-10-29 03:48:52

java模拟post请求发送json数据的相关文章

java模拟post请求发送json

java模拟post请求发送json,用两种方式实现,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求, 方法一: 1 package main.utils; 2 3 import java.io.*; 4 import java.net.HttpURLConnection; 5 import java.net.URL; 6 7 public class HttpUtilTest { 8 Log log = new Log(this.g

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

在进行程序之间数据通信时我们有时候就需要自定义二进制格式,然后通过HTTP进行二进制数据交互.交互的示例代码如下: public static void main(String[] args) { String result = ""; try { String url = "http://localhost:8080/Demo/SiteApi"; URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection co

java使用httpcomponents post发送json数据

一.适用场景 当我们向第三方系统提交数据的时候,需要调用第三方系统提供的接口.不同的系统提供的接口也不一样,有的是SOAP Webservice.RESTful Webservice 或其他的.当使用的是RESTful webservice的时候,就可以使用httpcomponents组件来完成调用. 如我们需要发起post请求,并将数据转成json格式,设置到post请求中并提交. url:"http://www.xxxxx.com/message" json数据格式 {"

java 模拟Http请求 提交图片和数据

1,伪造请求 package com.sxb.web.v2.wh.unittest; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.Input

Jersey框架put请求发送JSON数据

想用jersey框架发送post请求,body带json格式参数 url:http//192.168.1.211/api/test body 数据为 {"action":"test"} 实现如下: 注意事项:引用jar包一定要正确,不然调试一堆报错. 这里引用包如下: jettison-1.3.jar 这个提供JSONObject 如果用其它的可能会报各种错误. jersey-bundle-1.9.jar  这个是jersey的捆绑包,一个解决问题 javax.ws

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

jmeter中get请求gzip数据的方法: 在jmeter线程组中添加“http信息头管理器”,并添加名称:Accept-Encoding值: gzip,deflate注:HTTP信息头Accept-Encoding 是客户端发给服务器,声明客户端支持的编码类型 验证服务器是否返回了gzip格式数据: 1. 线程组中添加一个“查看结果树”监听器 2.运行测试后,在监听器取样器结果标签页查看http服务器的响应头: Content-Encoding: gzipVary: Accept-Encod

java使用https post发送json数据

package com.saygou.weixin; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlg

python发送post请求发送json数据时,报415的原因和处理方法。

415   Unsupported media type. 不支持MEDIA类型 这代表服务无法处理你提交的数据格式. 处理起来很简单,在你的header里指定一下格式. 加上一句代码 headers = {"Content-Type": "application/json"}

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

public static string PostMoths(string url, string param) { string strURL = url; System.Net.HttpWebRequest request; request = (System.Net.HttpWebRequest)WebRequest.Create(strURL); request.Method = "POST"; request.ContentType = "application/j