方式一: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. [css3]叉叉旋转效果

    .close_frame{display:inline-block;height:14px;width:14px;background:url("../images/closeiframe. ...

  2. hadoop机架感知与网络拓扑分析:NetworkTopology和DNSToSwitchMapping

    hadoop网络拓扑结构在整个系统中具有很重要的作用,它会影响DataNode的启动(注册).MapTask的分配等等.了解网络拓扑对了解整个hadoop的运行会有很大帮助. 首先通过下面两个图来了解 ...

  3. php导入excel

    使用phpexcelreader这个类文件来导入excel具体步骤: 先下载文件,然后引入phpexcelreader:下载地址:http://www.waaqi.com/wp-content/upl ...

  4. android异常: java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused

    android手机做下载文件时,报了如下异常: java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused 模拟器 ...

  5. Bootstrap <基础七>按钮

    任何带有 class .btn 的元素都会继承圆角灰色按钮的默认外观.但是 Bootstrap 提供了一些选项来定义按钮的样式,具体如下表所示: 以下样式可用于<a>, <butto ...

  6. myeclipse 快捷键大全

    转自:http://q.cnblogs.com/q/47190/ Technorati 标记: Shortcut keys Ctrl+1 快速修复(最经典的快捷键,就不用多说了)Ctrl+D: 删除当 ...

  7. Android按钮的各个样式设置

    安卓开发学习之014 Button应用详解(样式.背景.按钮单击.长按.双击.多击事件) 一.Button简介 按钮也是继承自TextView 二.XML定义方法 <Button android ...

  8. CSS 透明度 设置 兼容IE FF

    filter:Alpha(Opacity=80);/*IE*/ -moz-opacity:0.8;/*FF*/ opacity: 0.8;/*所有元素*/ 参数设置说明: Alpha(Opacity= ...

  9. 安装数据库Mocrosoft.NET Application Security警告

    在安装sqlserver 2012的时候,出现了Mocrosoft.NET Application Security警告,这个时候可以检查是否联网,如果没有联网请连接上,然后重新检查就不再警告了.如果 ...

  10. 整合了一个功能强大完善的OA系统源码,php全开源 界面漂亮美观

    整合了一个功能强大完善的OA系统源码,php全开源界面漂亮美观.需要的同学联系Q:930948049