方式一: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. Nehe Opengl

    http://nehe.gamedev.net/tutorial/lessons_01__05/22004/ Nehe Opengl,据说从基础到高端进阶都是很好的教程,准备学习这个序列,顺便记录下随 ...

  2. ImageLoader1

    package com.bawei.activity; import android.app.Activity; import android.graphics.Bitmap; import andr ...

  3. js实现图片预览

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...

  4. Java如何解决脆弱基类(基类被冻结)问题

    概述  大多数好的设计者象躲避瘟疫一样来避免使用实现继承(extends 关系).实际上80%的代码应该完全用interfaces写,而不是通过extends.“JAVA设计模式”一书详细阐述了怎样用 ...

  5. Add listitem with javascript 分类: Sharepoint 2015-07-16 20:23 4人阅读 评论(0) 收藏

    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', createListItem);//makes sure sp.js is loaded and the ...

  6. Python3学习(二)-递归函数、高级特性、切片

    ##import sys ##sys.setrecursionlimit(1000) ###关键字参数(**关键字参数名) ###与可变参数不同的是,关键字参数可以在调用函数时,传入带有参数名的参数, ...

  7. as3延迟处理

    查找关键字“flashplayer 弹性跑道” 每当一帧即将走完,FlashPlayer就要做些总结性工作(一次性地汇总变化),把这一帧当中发生的变化拿出来展示(渲染)一下. 如果它处理的事情少,工作 ...

  8. Bootstrap 模态框在用户点击背景空白处时会自动关闭

    问题: Bootstrap 模态框在用户点击背景空白处时,会自动关闭. 解决方法: 在HTML页面中编写模态框时,在div初始化时添加属性 aria-hidden=”true” data-backdr ...

  9. MySQL Workbench的使用教程 (初级入门版)

    MySQL Workbench 是 MySQL AB 最近释放的可视数据库设计工具.这个工具是设计 MySQL 数据库的专用工具. MySQL Workbench 拥有很多的功能和特性:这篇由Djon ...

  10. install graph-tool

    try this if ubuntu version is >= 14.04 sudo apt-get update sudo apt-get upgrade sudo apt-get -y i ...