服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java模拟post请求发送json的例子

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

2020-12-17 14:48veitch-w Java教程

本篇文章主要介绍了java模拟post请求发送json的例子,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

方法一:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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实现

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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;
  }

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

原文链接:http://www.cnblogs.com/veitch-623/p/6259008.html

延伸 · 阅读

精彩推荐