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. SpringBoot实战(五)之Thymeleaf

    Thymeleaf同jsp.volocity.freemarker等共同的职能是MVC模式中的视图展示层,即View. 当然了,SpringBoot中也可以用jsp,不过不推荐这种用法,比较推崇的就是 ...

  2. 枚举enum和enumerate

    #coding=utf-8 from enum import Enum #定义自己的枚举时需要使用class,继承Enum类 class Color(Enum): red=1 green=2 blue ...

  3. 【洛谷P2680】运输计划

    题目链接 题目大意: 一棵\(n\)个点的带边权的数,给定\(m\)条树上两点间的路径,现在你可以让树上任意一条边的权值变为零, 问如何选边使得\(m\)条路径中边权和最大的路径的边权和最小 \(\m ...

  4. Gradle Goodness: Parse Files with SimpleTemplateEngine in Copy Task

    With the copy task of Gradle we can copy files that are parsed by Groovy's SimpleTemplateEngine. Thi ...

  5. C#泛型约束 (转载)

    六种类型的约束: T:结构 类型参数必须是值类型.可以指定除 Nullable 以外的任何值类型.有关更多信息,请参见使用可空类型(C# 编程指南). T:类 类型参数必须是引用类型,包括任何类.接口 ...

  6. 用jQuery编写简单九宫格抽奖

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  7. DecimalFormat的使用

    DecimalFormat,四舍五入时需要设置RoundingMode 1.占位符0: 比实际数字的位数多,不足的地方用0补上. new DecimalFormat("00.00" ...

  8. 利用kage把msf变成可视化远控平台

    项目下载https://github.com/WayzDev/Kage/releases 这里用kali系统演示 1,先下载kage: 2,右击给予执行权限 3,启动msf msfconsole -q ...

  9. iOS OC与JS的交互(JavaScriptCore实现)

    本文包括JS调用OC方法并传值,OC调用JS方法并传值 本来想把html放进服务器里面,然后访问,但是觉得如果html在本地加载更有助于理解,特把html放进项目里 HTML代码 <!DOCTY ...

  10. Java 常见BUG 整理

    1.BigDecimal初始化double 2.Integer   java对于-128到127之间的数,会进行缓存,这个范围的Integer对象是同一个! == 是ok,但是超出这个范围就不可以用 ...