欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

java模拟post请求发送json的例子

时间:2021-09-08 09:26:30|栏目:JAVA代码|点击:

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

方法一:

package main.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtilTest {
  Log log = new Log(this.getClass());//初始化日志类
  /**
   * @作用 使用urlconnection
   * @param url
   * @param Params
   * @return
   * @throws IOException
   */
  public String sendPost(String url,String Params)throws IOException{
    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(Params);
      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();

      log.info(response.toString());
    } 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;
  }
}

方法二:使用httpclient实现

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import main.utils.Log;

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;

//post请求方法
  public String sendPost(String url, String data) {
    String response = null;
    log.info("url: " + url);
    log.info("request: " + data);
    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());
        log.info("response: " + response);
      } finally {
        if (httpclient != null) {
          httpclient.close();
        }
        if (httpresponse != null) {
          httpresponse.close();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return response;
  }

上一篇:idea的easyCode的 MybatisPlus模板的配置详解

栏    目:JAVA代码

下一篇:java比较器Comparable接口与Comaprator接口的深入分析

本文标题:java模拟post请求发送json的例子

本文地址:http://www.codeinn.net/misctech/173509.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有