欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-23 12:32:58
java模拟post请求发送json,用两种方式实现,第一种是httpurlconnection发送post请求,第二种是使用httpclient模拟post请求, 方法...

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;
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。