方式一: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请求的更多相关文章

  1. HttpClient方式模拟http请求设置头

    关于HttpClient方式模拟http请求,请求头以及其他参数的设置. 本文就暂时不给栗子了,当作简版参考手册吧. 发送请求是设置请求头:header HttpClient httpClient = ...

  2. Android 使用HttpClient方式提交POST请求

    final String username = usernameEditText.getText().toString().trim(); final String password = passwr ...

  3. Android 使用HttpClient方式提交GET请求

    public void httpClientGet(View view) { final String username = usernameEditText.getText().toString() ...

  4. 关于HttpClient模拟浏览器请求的參数乱码问题解决方式

    转载请注明出处:http://blog.csdn.net/xiaojimanman/article/details/44407297 http://www.llwjy.com/blogdetail/9 ...

  5. java发送短信--httpclient方式

    最近头让我写个发送短信的java程序检测BI系统,检查数据库是否有异常发送,有则发送短信到头的手机里.这里我直说httpclient方式的get请求方式,并且已经有方式的短信的接口了,所以只要再加上参 ...

  6. PHP-Curl模拟HTTPS请求

     使用PHP-Curl方式模拟HTTPS请求,测试接口传参和返回值状态   上代码!! <?php /** * 模拟post进行url请求 * @param string $url * @par ...

  7. HttpClientUtil [使用apache httpclient模拟http请求]

    基于httpclient-4.5.2 模拟http请求 以get/post方式发送json请求,并获取服务器返回的json -------------------------------------- ...

  8. 一步步教你为网站开发Android客户端---HttpWatch抓包,HttpClient模拟POST请求,Jsoup解析HTML代码,动态更新ListView

    本文面向Android初级开发者,有一定的Java和Android知识即可. 文章覆盖知识点:HttpWatch抓包,HttpClient模拟POST请求,Jsoup解析HTML代码,动态更新List ...

  9. 使用httpClient模拟http请求

    在很多场景下都需要用到java代码来发送http请求:如和短信后台接口的数据发送,发送数据到微信后台接口中: 这里以apache下的httpClient类来模拟http请求:以get和Post请求为例 ...

随机推荐

  1. 繁星——jquery的data()方法

    今天在看JQuery文档的时候偶然看到了data()方法,觉得挺好用的,这里做个记录. 这个方法用于在元素上存放数据,返回jQuery对象.在文档中提到V1.4.3 新增用法NEW data(obj) ...

  2. 详解.Net消息队列(MSMQ)应用

    [IT168 技术文档]MSMQ是Windows 2000.Windows XP.Windows Server 2003的一个组件,并将继续包含在Windows Vista和以后的Windows服务器 ...

  3. pod

    在运行 “sudo gem install cocoapods” 的时候出现问题:ERROR: While executing gem ... (Errno::EPERM)Operation not ...

  4. 记第一次TopCoder, 练习SRM 583 div2 250

    今天第一次做topcoder,没有比赛,所以找的最新一期的SRM练习,做了第一道题. 题目大意是说 给一个数字字符串,任意交换两位,使数字变为最小,不能有前导0. 看到题目以后,先想到的找规律,发现要 ...

  5. hypermesh2flac3d

    hypermesh2ansys2flac3d 目的: 将hypermesh中划分的网格输出到flac3d中.过程是hypermesh12.0-ansys13.0-flac3d3.0. 视频教程详见:h ...

  6. centos 7 下安装numpy、scipy等python包

    本文适用于刚入门的小白,欢迎大牛们批评指正. 因为要开始数据分析,而python又不像R和matlab那么简洁.需要安装的包很多~ 网上找了好多牛人博客,想在centos7下安装numpy,scipy ...

  7. IOS线程学习(一)

    1.NSThread  官方的描述 An NSThread object controls a thread of execution. Use this class when you want to ...

  8. Fragment的生命周期(三)

    自定义lifecycleoffragment布局文件 在main_activity布局中引用自定义的fragment布局 到logcat中查看程勋运行的结果 代码如下: 自定义的fragment布局: ...

  9. (l老陈-小石头)典型用户、用户故事、用例图

    一.典型用户 老陈 小石头 二.用户故事 老陈:作为一个家长,我希望能利用软件在电脑上储存一些数学题目,以便在繁忙的工作中也能帮助到孩子提高数学. 小石头:作为一个小学二年级的小学生,我希望能利用软件 ...

  10. 团队开发——冲刺2.e

    冲刺阶段二(第五天) 1.昨天做了什么? 讨论“暂停”功能:编写软件测试计划书(引言.测试内容). 2.今天准备做什么? A.编写软件使用说明书: B.编写软件测试计划书(测试规则.测试环境): C. ...