httpClient相对于java自带的请求功能更加强大,下面就以例子的形式给出:
//HttpClient Get请求
private static void register() {
try {
System.out.println("--------------START---------------");
String url="http://218.17.39.35:8100/acc_accInfo.htm?tkn=E02F67F63771E687504EED1A48A6D194C2A5DD0978F96127944B875E6BE07B95&method=u_accInfo";
HttpClient httpClient = HttpClients.createDefault();
HttpPost get = new HttpPost(url);
get.setHeader("Cookie", "JSESSIONID=8195A9B97D3104D9BE0081A40942DD4E");
HttpResponse response = httpClient.execute(get);
String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(responseString);
System.out.println("--------------END---------------");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* httpClient中的post请求
*
* @param mobile
*
* @Description: httpClient中的post请求
*/
private static void register(String mobile) {
try {
System.out.println("--------------START---------------");
HttpClient client = HttpClients.createDefault();
String url = "http://218.17.39.35:8100/aut_smsCode.hts";
HttpPost post = new HttpPost(url);
post.setHeader("Cookie", "JSESSIONID=1983025ECD57A5E17A1E8352DF67D7A7");
Map<String, String> map = new HashMap<String, String>();
//参数
map.put("mobile", mobile);
//map.put("checkCode", "YUJH");
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
for (Map.Entry<String, String> m : map.entrySet()) {
BasicNameValuePair pair = new BasicNameValuePair(m.getKey(), m.getValue());
params.add(pair);
}
HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(responseString);
System.out.println("--------------END---------------");
} catch (IOException e) {
e.printStackTrace();
}
}
===============================================================================
以下分别是:
1、URLENCODE格式的httpClient post请求
2、json格式的httpClient post请求
3、xml格式的httpClient post请求
/**
* 短连接发送(不进行URLENCODE)
*
* @description httpClient的URLENCODE请求时间
* @param obj 请求对象
* @param httpUrl 请求地址http://114.67.62.211:7901/sms/v2/std/single_send
* @return 请求网关返回的值
* @throws Exception
*/
private String executeNotKeepAliveNotUrlEncodePost(Object obj, String httpUrl) throws Exception
{
String result = String.valueOf("-310099");
HttpClient httpclient = null;
try
{
Class cls = obj.getClass();
Field[] fields = cls.getDeclaredFields();
// 定义变量
String fieldName = null;
String fieldNameUpper = null;
Method getMethod = null;
Object value = null;
String entityValue = "";
//循环拼接请求参数
for (int i = 0; i < fields.length; i++)
{
fieldName = fields[i].getName();
fieldNameUpper = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
getMethod = cls.getMethod("get" + fieldNameUpper);
value = getMethod.invoke(obj);
if(value != null)
{
//拼接请求参数
entityValue += fieldName + "=" + String.valueOf(value) + "&";
}
}
// 定义请求头
HttpPost httppost = new HttpPost(httpUrl);
httppost.setHeader("Content-Type", "text/x-www-form-urlencoded");
// 去掉最后一个&符号
entityValue = entityValue.substring(0, entityValue.length() - 1);
StringEntity stringEntity = new StringEntity(entityValue, HTTP.UTF_8);
// 设置参数的编码UTF-8
httppost.setEntity(stringEntity);
// 创建连接
httpclient = new DefaultHttpClient();
// 设置请求超时时间 设置为5秒
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, "5 * 1000");
// 设置响应超时时间 设置为60秒
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, "5 * 1000");
HttpEntity entity = null;
HttpResponse httpResponse=null;
try
{
// 向网关请求
httpResponse=httpclient.execute(httppost);
// 若状态码为200,则代表请求成功
if(httpResponse!=null && httpResponse.getStatusLine().getStatusCode()==200)
{
//获取响应的实体
entity=httpResponse.getEntity();
//响应的内容不为空,并且响应的内容长度大于0,则获取响应的内容
if(entity != null && entity.getContentLength() > 0)
{
try
{
//请求成功,能获取到响应内容
result = EntityUtils.toString(entity);
}
catch (Exception e)
{
e.printStackTrace();
//获取内容失败,返回空字符串
result="";
}
}else
{
//请求成功,但是获取不到响应内容
result="";
}
}else
{
// 设置错误码
result = String.valueOf("-310099");
System.out.println("请求失败:"+httpResponse.getStatusLine().toString());
}
}catch (Exception e)
{
result = String.valueOf("-310099");
e.printStackTrace();
}
}
catch (Exception e)
{
result = String.valueOf("-310099");
e.printStackTrace();
}
finally
{
// 关闭连接
if(httpclient != null)
{
try
{
httpclient.getConnectionManager().shutdown();
}
catch (Exception e2)
{
// 关闭连接失败
e2.printStackTrace();
}
}
}
return result;
}
/**
* 短连接发送(进行URLENCODE)
*
* @description
* @param obj 请求对象
* @param httpUrl 请求地址
* @return 请求网关返回的值
* @throws Exception
*/
private String executeNotKeepAlivePost(Object obj, String httpUrl) throws Exception
{
String result = String.valueOf("-310099");
HttpClient httpclient = null;
try
{
Class cls = obj.getClass();
Field[] fields = cls.getDeclaredFields();
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
// 定义变量
String fieldName = null;
String fieldNameUpper = null;
Method getMethod = null;
Object value = null;
// 设置请求参数
for (int i = 0; i < fields.length; i++)
{
fieldName = fields[i].getName();
fieldNameUpper = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
getMethod = cls.getMethod("get" + fieldNameUpper);
value = getMethod.invoke(obj);
if(value != null)
{
//拼接请求参数
params.add(new BasicNameValuePair(fieldName, String.valueOf(value)));
}
}
// 定义请求头
HttpPost httppost = new HttpPost(httpUrl);
// 设置参数的编码UTF-8
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
// 创建连接
httpclient = new DefaultHttpClient();
// 设置请求超时时间 设置为5秒
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, "5 * 1000");
// 设置响应超时时间 设置为60秒
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, "5 * 1000");
HttpEntity entity = null;
HttpResponse httpResponse=null;
try
{
// 向网关请求
httpResponse=httpclient.execute(httppost);
// 若状态码为200,则代表请求成功
if(httpResponse!=null && httpResponse.getStatusLine().getStatusCode()==200)
{
//获取响应的实体
entity=httpResponse.getEntity();
//响应的内容不为空,并且响应的内容长度大于0,则获取响应的内容
if(entity != null && entity.getContentLength() > 0)
{
try
{
//请求成功,能获取到响应内容
result = EntityUtils.toString(entity);
}
catch (Exception e)
{
e.printStackTrace();
//获取内容失败,返回空字符串
result="";
}
}else
{
//请求成功,但是获取不到响应内容
result="";
}
}else
{
// 设置错误码
result = String.valueOf("-310099");
System.out.println("请求失败:"+httpResponse.getStatusLine().toString());
}
}catch (Exception e)
{
result = String.valueOf("-310099");
e.printStackTrace();
}
}
catch (Exception e)
{
result = String.valueOf("-310099");
e.printStackTrace();
}
finally
{
// 关闭连接
if(httpclient != null)
{
try
{
httpclient.getConnectionManager().shutdown();
}
catch (Exception e2)
{
// 关闭连接失败
e2.printStackTrace();
}
}
}
return result;
}
/**
* json格式的httpClient请求
*
* @description 短连接发送(不进行URLENCODE)
* @param obj 请求对象
* @param httpUrl 请求地址
* @return 请求网关返回的值
* @throws Exception
*/
private String executeNotKeepAliveNotUrlEncodePost(Object obj, String httpUrl) throws Exception
{
String result = String.valueOf(ERROR_310099);
HttpClient httpclient = null;
try
{
//将实体对象,生成JSON字符串
String entityValue = gson.toJson(obj);
// 定义请求头
HttpPost httppost = new HttpPost(httpUrl);
httppost.setHeader("Content-Type", "text/json");
StringEntity stringEntity = new StringEntity(entityValue, HTTP.UTF_8);
// 设置参数的编码UTF-8
httppost.setEntity(stringEntity);
// 创建连接
httpclient = new DefaultHttpClient();
// 设置请求超时时间 设置为5秒
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, HTTP_REQUEST_TIMEOUT);
// 设置响应超时时间 设置为60秒
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, HTTP_RESPONSE_TIMEOUT);
HttpEntity entity = null;
HttpResponse httpResponse=null;
try
{
// 向网关请求
httpResponse=httpclient.execute(httppost);
// 若状态码为200,则代表请求成功
if(httpResponse!=null && httpResponse.getStatusLine().getStatusCode()==200)
{
//获取响应的实体
entity=httpResponse.getEntity();
//响应的内容不为空,并且响应的内容长度大于0,则获取响应的内容
if(entity != null)
{
try
{
//请求成功,能获取到响应内容
result = EntityUtils.toString(entity);
}
catch (Exception e)
{
e.printStackTrace();
//获取内容失败,返回空字符串
result="";
}
}else
{
//请求成功,但是获取不到响应内容
result="";
}
}else
{
// 设置错误码
result = String.valueOf(ERROR_310099);
System.out.println("请求失败:"+httpResponse.getStatusLine().toString());
}
}catch (Exception e)
{
result = String.valueOf(ERROR_310099);
e.printStackTrace();
}
}
catch (Exception e)
{
result = String.valueOf(ERROR_310099);
e.printStackTrace();
}
finally
{
// 关闭连接
if(httpclient != null)
{
try
{
httpclient.getConnectionManager().shutdown();
}
catch (Exception e2)
{
// 关闭连接失败
e2.printStackTrace();
}
}
}
return result;
}
/**
* xml格式的httpClient post请求
*
* @description 短连接发送(不进行URLENCODE)
* @param obj 请求对象
* @param httpUrl 请求地址
* @param methodName 方法名
* @return 请求网关返回的值
* @throws Exception
*/
private String executeNotKeepAliveNotUrlEncodePost(Message message, String httpUrl,String methodName) throws Exception
{
String result = String.valueOf(ERROR_310099);
HttpClient httpclient = null;
try
{
//XML请求报文
StringBuffer requestSb=new StringBuffer("<?xml version="1.0" encoding="utf-8"?>");
//发送增加标签
if("template_send".equals(methodName)){
requestSb.append("<mtreq>");
}else if("get_rpt".equals(methodName))
{
//状态报告
requestSb.append("<rptreq>");
}else if("get_balance".equals(methodName))
{
//余额
requestSb.append("<feereq>");
}
//根据是否有值,生成XML报文
// 用户账号
if(message.getUserid()!=null)
{
requestSb.append("<userid>").append(message.getUserid()).append("</userid>");
}
// 用户密码
if(message.getPwd()!=null)
{
requestSb.append("<pwd>").append(message.getPwd()).append("</pwd>");
}
//手机号
if(message.getMobile()!=null)
{
requestSb.append("<mobile>").append(message.getMobile()).append("</mobile>");
}
//短信内容
if(message.getContent()!=null&&!"".equals(message.getContent()))
{
requestSb.append("<content>").append(message.getContent()).append("</content>");
}
//时间戳
if(message.getTimestamp()!=null)
{
requestSb.append("<timestamp>").append(message.getTimestamp()).append("</timestamp>");
}
// 回拨显示的号码
if(message.getExno()!=null)
{
requestSb.append("<exno>").append(message.getExno()).append("</exno>");
}
//用户自定义流水编号
if(message.getCustid()!=null)
{
requestSb.append("<custid>").append(message.getCustid()).append("</custid>");
}
//模板ID
if(message.getTmplid()!=null)
{
requestSb.append("<tmplid>").append(message.getTmplid()).append("</tmplid>");
}
//消息类型
if(message.getMsgtype()!=null)
{
requestSb.append("<msgtype>").append(message.getMsgtype()).append("</msgtype>");
}
//获取状态报告的最大条数
if(message.getRetsize()!=null)
{
requestSb.append("<retsize>").append(message.getRetsize()).append("</retsize>");
}
//发送增加标签
if("template_send".equals(methodName)){
requestSb.append("</mtreq>");
}else if("get_rpt".equals(methodName))
{
//状态报告
requestSb.append("</rptreq>");
}else if("get_balance".equals(methodName))
{
//余额
requestSb.append("</feereq>");
}
String entityValue=requestSb.toString();
// 定义请求头
HttpPost httppost = new HttpPost(httpUrl);
httppost.setHeader("Content-Type", "text/xml");
StringEntity stringEntity = new StringEntity(entityValue, HTTP.UTF_8);
// 设置参数的编码UTF-8
httppost.setEntity(stringEntity);
// 创建连接
httpclient = new DefaultHttpClient();
// 设置请求超时时间 设置为5秒
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, HTTP_REQUEST_TIMEOUT);
// 设置响应超时时间 设置为60秒
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, HTTP_RESPONSE_TIMEOUT);
HttpEntity entity = null;
HttpResponse httpResponse=null;
try
{
// 向网关请求
httpResponse=httpclient.execute(httppost);
// 若状态码为200,则代表请求成功
if(httpResponse!=null && httpResponse.getStatusLine().getStatusCode()==200)
{
//获取响应的实体
entity=httpResponse.getEntity();
//响应的内容不为空,并且响应的内容长度大于0,则获取响应的内容
if(entity != null)
{
try
{
//请求成功,能获取到响应内容
result = EntityUtils.toString(entity);
}
catch (Exception e)
{
e.printStackTrace();
//获取内容失败,返回空字符串
result="";
}
}else
{
//请求成功,但是获取不到响应内容
result="";
}
}else
{
// 设置错误码
result = String.valueOf(ERROR_310099);
System.out.println("请求失败:"+httpResponse.getStatusLine().toString());
}
}catch (Exception e)
{
result = String.valueOf(ERROR_310099);
e.printStackTrace();
}
}
catch (Exception e)
{
result = String.valueOf(ERROR_310099);
e.printStackTrace();
}
finally
{
// 关闭连接
if(httpclient != null)
{
try
{
httpclient.getConnectionManager().shutdown();
}
catch (Exception e2)
{
// 关闭连接失败
e2.printStackTrace();
}
}
}
return result;
}