HttpClient方式模拟http请求
方式一:HttpClient
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger; import java.io.*;
import java.util.*; /**
* Created by Chen Hongyu on 2016/5/17.
*/
public class HttpTookit {
private static Logger LOGGER = Logger.getLogger(HttpTookit.class); /**
* @param args
* @throws IOException
* @throws ClientProtocolException
*/
public static void main(String[] args) throws ClientProtocolException, IOException { String urlPost = "http://localhost:8080/collectDataPost.do";
String urlGet = "http://localhost:8080/collectDataGet.do?name=张三"; Map<String, object> params = new HashMap<>();
params.put("name", "jerry");
params.put("age", "18");
params.put("sex", "man");
String respon = doPost(urlPost, params);
System.out.println("================发送请求:" + params);
System.out.println("================回掉结果:" + respon); } public static void doGet(String url) {
try {
// 创建HttpClient实例
HttpClient httpclient = new DefaultHttpClient();
// 创建Get方法实例
HttpGet httpgets = new HttpGet(url);
HttpResponse response = httpclient.execute(httpgets);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instreams = entity.getContent();
String str = convertStreamToString(instreams);
System.out.println("Do something");
System.out.println(str);
// Do not need the rest
httpgets.abort();
}
} catch (Exception e) { }
} public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder(); String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
} public static String doPost(String url, Map<String, String> map) { HttpClient httpClient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
method.setHeader("accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); int status = 0;
String body = null; if (method != null & map != null) {
try {
//建立一个NameValuePair数组,用于存储欲传送的参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : map.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
//添加参数
method.setEntity(new UrlEncodedFormEntity(params)); long startTime = System.currentTimeMillis(); HttpResponse response = httpClient.execute(method); System.out.println("the http method is:" + method.getEntity());
long endTime = System.currentTimeMillis();
int statusCode = response.getStatusLine().getStatusCode();
LOGGER.info("状态码:" + statusCode);
LOGGER.info("调用API 花费时间(单位:毫秒):" + (endTime - startTime));
if (statusCode != HttpStatus.SC_OK) {
LOGGER.error("请求失败:" + response.getStatusLine());
status = 1;
} //Read the response body
body = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (IOException e) {
//发生网络异常
LOGGER.error("exception occurred!\n" + ExceptionUtils.getFullStackTrace(e));
//网络错误
status = 3;
} finally {
LOGGER.info("调用接口状态:" + status);
} }
return body;
} }
方式二:HttpURLConnection
import java.io.*;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map; /**
* HTTP工具
* Created by Chen Hongyu on 2016/5/18.
*/
public class HttpUtil {
/**
* 请求类型: GET
*/
public final static String GET = "GET";
/**
* 请求类型: POST
*/
public final static String POST = "POST"; /**
* HttpURLConnection方式 模拟Http Get请求
* @param urlStr
* 请求路径
* @param paramMap
* 请求参数
* @return
* @throws Exception
*/
public static String get(String urlStr, Map<String, String> paramMap) throws Exception {
urlStr = urlStr + "?" + getParamString(paramMap);
HttpURLConnection conn = null;
try {
//创建URL对象
URL url = new URL(urlStr);
//获取URL连接
conn = (HttpURLConnection) url.openConnection();
//设置通用的请求属性
setHttpUrlConnection(conn, GET);
//建立实际的连接
conn.connect();
//获取响应的内容
return readResponseContent(conn.getInputStream());
} finally {
if (null != conn)
conn.disconnect();
}
} /**
* HttpURLConnection方式 模拟Http Post请求
* @param urlStr
* 请求路径
* @param paramMap
* 请求参数
* @return
* @throws Exception
*/
public static String post(String urlStr, Map<String, String> paramMap) throws Exception {
HttpURLConnection conn = null;
PrintWriter writer = null;
try {
//创建URL对象
URL url = new URL(urlStr);
//获取请求参数
String param = getParamString(paramMap);
//获取URL连接
conn = (HttpURLConnection) url.openConnection();
//设置通用请求属性
setHttpUrlConnection(conn, POST);
//建立实际的连接
conn.connect();
//将请求参数写入请求字符流中
writer = new PrintWriter(conn.getOutputStream());
writer.print(param);
writer.flush();
//读取响应的内容
return readResponseContent(conn.getInputStream());
} finally {
if (null != conn)
conn.disconnect();
if (null != writer)
writer.close();
}
} /**
* 读取响应字节流并将之转为字符串
* @param in
* 要读取的字节流
* @return
* @throws IOException
*/
private static String readResponseContent(InputStream in) throws IOException {
Reader reader = null;
StringBuilder content = new StringBuilder();
try {
reader = new InputStreamReader(in);
char[] buffer = new char[1024];
int head = 0;
while ((head = reader.read(buffer)) > 0) {
content.append(new String(buffer, 0, head));
}
return content.toString();
} finally {
if (null != in)
in.close();
if (null != reader)
reader.close();
}
} /**
* 设置Http连接属性
* @param conn
* http连接
* @return
* @throws ProtocolException
* @throws Exception
*/
private static void setHttpUrlConnection(HttpURLConnection conn,
String requestMethod) throws ProtocolException {
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("content-encoding", "utf8");
conn.setRequestProperty("accept", "application/json");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Accept-Language", "zh-CN");
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
conn.setRequestProperty("Proxy-Connection", "Keep-Alive"); System.out.println(conn.getRequestMethod());
if (null != requestMethod && POST.equals(requestMethod)) {
conn.setDoOutput(true);
conn.setDoInput(true);
}
} /**
* 将参数转为路径字符串
* @param paramMap
* 参数
* @return
*/
private static String getParamString(Map<String, String> paramMap) {
if (null == paramMap || paramMap.isEmpty()) {
return "";
}
StringBuilder builder = new StringBuilder();
for (String key : paramMap.keySet()) {
builder.append("&").append(key).append("=").append(paramMap.get(key));
}
return new String(builder.deleteCharAt(0).toString());
} public static void main(String[] args) throws UnsupportedEncodingException {
String url = "http://localhost:8080/collectData.do"; Map<String, String> params = new HashMap<>(); params.put("name", "jerry");
params.put("age", "18");
params.put("sex", "man"); try {
System.out.println(post(url, mapParam));
} catch (Exception e) {
e.printStackTrace();
}
}
}
转自:其他(已找不到原文)
若有侵权,请联系本人:chennhy201248@sina.com
HttpClient方式模拟http请求的更多相关文章
- HttpClient方式模拟http请求设置头
关于HttpClient方式模拟http请求,请求头以及其他参数的设置. 本文就暂时不给栗子了,当作简版参考手册吧. 发送请求是设置请求头:header HttpClient httpClient = ...
- Android 使用HttpClient方式提交POST请求
final String username = usernameEditText.getText().toString().trim(); final String password = passwr ...
- Android 使用HttpClient方式提交GET请求
public void httpClientGet(View view) { final String username = usernameEditText.getText().toString() ...
- 关于HttpClient模拟浏览器请求的參数乱码问题解决方式
转载请注明出处:http://blog.csdn.net/xiaojimanman/article/details/44407297 http://www.llwjy.com/blogdetail/9 ...
- java发送短信--httpclient方式
最近头让我写个发送短信的java程序检测BI系统,检查数据库是否有异常发送,有则发送短信到头的手机里.这里我直说httpclient方式的get请求方式,并且已经有方式的短信的接口了,所以只要再加上参 ...
- PHP-Curl模拟HTTPS请求
使用PHP-Curl方式模拟HTTPS请求,测试接口传参和返回值状态 上代码!! <?php /** * 模拟post进行url请求 * @param string $url * @par ...
- HttpClientUtil [使用apache httpclient模拟http请求]
基于httpclient-4.5.2 模拟http请求 以get/post方式发送json请求,并获取服务器返回的json -------------------------------------- ...
- 一步步教你为网站开发Android客户端---HttpWatch抓包,HttpClient模拟POST请求,Jsoup解析HTML代码,动态更新ListView
本文面向Android初级开发者,有一定的Java和Android知识即可. 文章覆盖知识点:HttpWatch抓包,HttpClient模拟POST请求,Jsoup解析HTML代码,动态更新List ...
- 使用httpClient模拟http请求
在很多场景下都需要用到java代码来发送http请求:如和短信后台接口的数据发送,发送数据到微信后台接口中: 这里以apache下的httpClient类来模拟http请求:以get和Post请求为例 ...
随机推荐
- 【转】valueof()用法
valueOf()用来返回对象的原始类型的值. 语法 booleanObject.valueOf() 代码:<script> var a = new String("valueO ...
- UAC在注册表中的对应位置
UAC在注册表中的对应位置 HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Policies/System 相关键值设置: U ...
- 关于ssh上传文件
今天用ssh传项目到公司总部的服务器上,报了错误: encountered 1 errors during the transfer 重启ssh再次上传还是一样的错误,然后我让公司那里重启一下服务器, ...
- linux环境下安装oracle数据库 原文在卡卡100http://www.cnblogs.com/kaka100
centos55_oracle11gr2_install 第一个阶段:安装centos55 a:安装centos5.5 用图形界面安装 硬盘 16G 注意:用图形界面安装.. 第二个阶段:配 ...
- T-Shirt 估算法
T-Shirt Size Estimation (2015-05-11 22:58:18) 转载▼ 产出:产品经理会对每一条需求评估上业务影响力的尺寸,如:XXXL 影响一千万人以上或是可以占 ...
- Paths_Quartz2D
Paths中的几个重要元素 Points void CGContextMoveToPoint ( CGContextRef c, CGFloat x, CGFloat y ); 指定 ...
- C# 大小写转换,方便index of
ToUpper:小写转大写ToLower:大写转小写 例: string str=120cm*150g/m2;从中取出120和150,但是又要规避大小写问题,这时候就需要将str转换为大写,然后ind ...
- 初学js
接触时感觉跟前面写网页的差距和大,与c语言很相似.主要学的有: 1.引入js的三种方法:外联,内联,嵌套 2.标识符:第一个字符可以是任意Unicode字母,以及美元符号($)和下划线(_). - 第 ...
- 【转】Linux Top 命令解析 比较详细
TOP命令是Linux下常用的性能分析工具,能够实时显示系统中各个进程的资源占用状况. TOP是一个动态显示过程,即可以通过用户按键来不断刷新当前状态.如果在前台执行该命令,它将独占前台,直到用户 ...
- sql server 2012提示:评估期已过 的解决办法 附序列号
sql server 2012提示评估期已过的解决方法: 第一步:进入SQL2012配置工具中的安装中心. 第二步:再进入左侧维护选项界面,然后选择选择版本升级. 第三步:进入输入产品密钥界面,输入相 ...