java模拟http发送请求,第一种是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;
}

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

 

java模拟http请求的更多相关文章

  1. 上curl java 模拟http请求

    最近,我的项目要求java模拟http请求,获得dns解决 tcp处理过的信息特定的连接. java api提供urlConnection apache提供的httpClient都不能胜任该需求,二次 ...

  2. curl java 模拟http请求

    curl java 模拟http请求 直接上代码: public static void main(String args[]) throws Exception { String url = &qu ...

  3. java模拟post请求发送json

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

  4. Java模拟http请求调用远程接口工具类

    package ln; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamRea ...

  5. Java 模拟http请求

    package ln; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamRea ...

  6. java模拟http请求(代理ip)

    java实现动态切换上网IP (ADSL拨号上网) java动态设置IP java模拟http的Get/Post请求 自动生成IP模拟POST访问后端程序 JAVA 动态替换代理IP并模拟POST

  7. Java模拟http请求远程调用接口工具类

    package ln; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamRea ...

  8. java模拟http请求上传文件,基于Apache的httpclient

    1.依赖 模拟http端的请求需要依赖Apache的httpclient,需要第三方JSON支持,项目中添加 <dependency> <groupId>org.apache& ...

  9. Java模拟POST请求发送二进制数据

    在进行程序之间数据通信时我们有时候就需要自定义二进制格式,然后通过HTTP进行二进制数据交互.交互的示例代码如下: public static void main(String[] args) { S ...

随机推荐

  1. webpack中使用babel处理es6语法

    index.js const arr = [ new Promise(()=>{}), new Promise(()=>{}) ]; arr.map(item => { consol ...

  2. 测试用例组合--PICT

    测试用例组合 一原理 1.配对组合原理(两两组合原理),应用工具PICT自动输出组合 name=a,b value=1,2 key=m,n 如果自己组合那么有2*2*2=8条用例 a1m a2m a1 ...

  3. win2003 HookPort 服务启动失败的解决办法!

    Win2003系统每次开机启动时都弹出个对话框报HookPort 服务启动失败,很多网友都遇到同类问题,问题根源是360安全卫士引起的,官方一直没有给出解决方案 问题描述:Win2003系统每次开机启 ...

  4. 数据库事务ACID特性及隔离级别

    数据库ACID特性介绍 1.原子性(Atomic)一个事务被视为一个不可分割的最小工作单元,这个事务里的所有操作要么全部成功执行,要么全都不执行,不能只执行其中的一部分操作.实现事务的原子性,要支持回 ...

  5. standby_file_management 参数为manual 导致ORA-01111问题

    情景: Dataguard 物理备库执行恢复报错: Errors in file /home/u01/app/diag/rdbms/rzorcl11g/ORCL/trace/ORCL_pr00_358 ...

  6. 偏前端 - ios下position:fixed失效的问题解决

    如图,考虑到用户体验的问题,一般页面的下方提交按钮都会随着固定在页面上,方便用户点击. 有些人肯定就说了,这还不简单,position:fixed: 但是在ios这个坑货系统上这个position:f ...

  7. jq写无缝轮播

    今天分享一下我自己早几天写的一个效果:无缝轮播,虽然不难,很简单,也没有封装处理过,但是还是希望能帮到一些前端的小伙伴吧,如果有小伙伴感觉有更简化的写法希望可以一起交流一下,技术在于交流嘛,我的邮箱是 ...

  8. transfrom、transition、animation区别

    transfrom transform是静态属性,非动画属性,和margin-left.margin-top类似. translate:平移,类似position:relative;translate ...

  9. 常用PHP方法

    个人常用的一些方法记录/** * 返回错误 * * @param int $err_no * @param string $err_msg * @param array $data * @return ...

  10. helpera64开发板下制作ubuntu rootfs镜像(二)

    上一篇路径:https://www.cnblogs.com/jizizh/p/10380513.html Helpera64开发板ubuntu剩于工作: 1.背光调节 答:/sys/class/bac ...