您的位置:首页 > 理论基础 > 计算机网络

HttpClient方式模拟http请求

2016-05-26 17:08 411 查看

方式一: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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: