温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java中的json怎么利用post请求进行发送

发布时间:2020-12-02 15:40:00 来源:亿速云 阅读:226 作者:Leah 栏目:编程语言

这篇文章给大家介绍java中的json怎么利用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;
  }

关于java中的json怎么利用post请求进行发送就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI