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. BZOJ1731:[USACO]Layout 排队布局(差分约束)

    Description Like everyone else, cows like to stand close to their friends when queuing for feed. FJ ...

  2. P2564 [SCOI2009]生日礼物

    题目背景 四川2009NOI省选 题目描述 小西有一条很长的彩带,彩带上挂着各式各样的彩珠.已知彩珠有N个,分为K种.简单的说,可以将彩带考虑为x轴,每一个彩珠有一个对应的坐标(即位置).某些坐标上可 ...

  3. JavaScript脚本的执行原理?

    JavaScript是一种动态.弱类型.基于原型的语言,通过浏览器可以直接执行. 当浏览器遇到\<script>标记的时候,浏览器会执行之间的JavaScript代码.嵌入的js代码是顺序 ...

  4. App测试需要测什么

    App,做为当下最热的手机安装软件,无论是产品本身的设计还是性能,易用性等都是非常受考验.一个app能在用户的手机上使用,并作为一个长期用户是非常不容易的.那么,App的测试中我们到底要测试什么呢? ...

  5. CodeForces - 999D Equalize the Remainders (模拟+set)

    You are given an array consisting of nn integers a1,a2,…,ana1,a2,…,an , and a positive integer mm . ...

  6. Vue聊天框默认滚动到底部

    功能场景 在开发中,我们总能遇到某些场景需要运用到聊天框,比如客服对话.如果你不是一名开发人员,可能你在使用QQ或者聊天工具的时候并没有注意到,当你发出一条消息的时候,窗体会默认滚动到最底部,让用户可 ...

  7. 【css】 如何修改select的样式

    select { /*清除select默认样式*/ appearance:none; -moz-appearance:none; -webkit-appearance:none; -ms-appear ...

  8. JS如何截取-后面的字符串

    str为要截取的字符串  通过获取字符串中“-”的坐标index,其他特殊字符以此类推 var index=str.lastIndexOf("\-"); str=str.subst ...

  9. SQLServer禁用、启用外键约束

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ---启用or禁用指定表所有外键约束  alter table PUB_STRU  NOCHECK constrai ...

  10. SQL循环插入批量数据

    declare @i intdeclare @qid int set @i=1set @qid=100 while @i<50000begininsert into Order(orderid, ...