博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java模拟http请求
阅读量:5111 次
发布时间:2019-06-13

本文共 4049 字,大约阅读时间需要 13 分钟。

java模拟http发送请求,第一种是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.getClass());//初始化日志类 9     /**10      * @作用 使用urlconnection11      * @param url12      * @param Params13      * @return14      * @throws IOException15      */16     public String sendPost(String url,String Params)throws IOException{17         OutputStreamWriter out = null;18         BufferedReader reader = null;19         String response="";20         try {21             URL httpUrl = null; //HTTP URL类 用这个类来创建连接22             //创建URL23             httpUrl = new URL(url);24             //建立连接25             HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();26             conn.setRequestMethod("POST");27             conn.setRequestProperty("Content-Type", "application/json");28             conn.setRequestProperty("connection", "keep-alive");29             conn.setUseCaches(false);//设置不要缓存30             conn.setInstanceFollowRedirects(true);31             conn.setDoOutput(true);32             conn.setDoInput(true);33             conn.connect();34             //POST请求35             out = new OutputStreamWriter(36                     conn.getOutputStream());37             out.write(Params);38             out.flush();39             //读取响应40             reader = new BufferedReader(new InputStreamReader(41                     conn.getInputStream()));42             String lines;43             while ((lines = reader.readLine()) != null) {44                 lines = new String(lines.getBytes(), "utf-8");45                 response+=lines;46             }47             reader.close();48             // 断开连接49             conn.disconnect();50 51             log.info(response.toString());52         } catch (Exception e) {53         System.out.println("发送 POST 请求出现异常!"+e);54         e.printStackTrace();55         }56         //使用finally块来关闭输出流、输入流57         finally{58         try{59             if(out!=null){60                 out.close();61             }62             if(reader!=null){63                 reader.close();64             }65         }66         catch(IOException ex){67             ex.printStackTrace();68         }69     }70 71         return response;72     }73 }

 

 方法二:使用httpclient实现

1 import java.io.UnsupportedEncodingException; 2 import java.net.URLEncoder; 3  4 import main.utils.Log; 5  6 import org.apache.http.client.methods.CloseableHttpResponse; 7 import org.apache.http.client.methods.HttpPost; 8 import org.apache.http.entity.ContentType; 9 import org.apache.http.entity.StringEntity;10 import org.apache.http.impl.client.CloseableHttpClient;11 import org.apache.http.impl.client.HttpClients;12 import org.apache.http.util.EntityUtils;13 14 //post请求方法15 public  String sendPost(String url, String data) {16    String response = null;17    log.info("url: " + url);18    log.info("request: " + data);19    try {20        CloseableHttpClient httpclient = null;21        CloseableHttpResponse httpresponse = null;22        try {23            httpclient = HttpClients.createDefault();24            HttpPost httppost = new HttpPost(url);25            StringEntity stringentity = new StringEntity(data,26                    ContentType.create("text/json", "UTF-8"));27            httppost.setEntity(stringentity);28            httpresponse = httpclient.execute(httppost);29            response = EntityUtils30                    .toString(httpresponse.getEntity());31            log.info("response: " + response);32        } finally {33            if (httpclient != null) {34                httpclient.close();35            }36            if (httpresponse != null) {37                httpresponse.close();38            }39        }40    } catch (Exception e) {41        e.printStackTrace();42    }43    return response;44 }

 

 

附:httpClient 4.3中文手册,来自开源中国:https://my.oschina.net/u/565871/blog/701214

 

 

转载于:https://www.cnblogs.com/veitch-623/p/6259008.html

你可能感兴趣的文章
ENVISAT ASAR 文件命名规则
查看>>
后端传输数据到前端
查看>>
Export class type
查看>>
通过反射来修改对象里面的值
查看>>
Gym - 100221D 一题一直没过的dfs,,应该是纯手动码?
查看>>
Codeforces Round #172 (Div. 2) D. Maximum Xor Secondary 单调栈应用
查看>>
...
查看>>
关于大根堆 (模板)
查看>>
堆排序
查看>>
java 垃圾回收总结(可达性分析 引用分类
查看>>
洛谷 P2024 [NOI2001]食物链 (并查集)
查看>>
python之路_socketserver模块
查看>>
GreenDao数据库的简单使用
查看>>
jquery判断输入框的字符串是否为空或者空格
查看>>
NYOJ-44 简单DP
查看>>
java Integer与int详解 01
查看>>
JAVA对存储过程的调用方法(本文源于网络)
查看>>
排序思想
查看>>
linux服务器git pull/push时提示输入账号密码之免除设置
查看>>
第一阶段冲刺8
查看>>