HttpClient 实际小应用

来源:互联网 发布:caffe windows github 编辑:程序博客网 时间:2024/05/21 09:30
工作中根据公司代码风格编写的HttpClient测试Util,有需要的同事可以借用下;
HttpClient入门地址:https://www.ibm.com/developerworks/cn/opensource/os-httpclient/
代码如下:

import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpStatus;import org.apache.commons.httpclient.NameValuePair;import org.apache.commons.httpclient.methods.PostMethod;import com.google.gson.Gson;public class HttpClientUtil { /**  *   * @param reqList 访问的参数,注意查看代码中的解析List中的Map只有两个值 key 与 value

  * @param url  访问的地址  * @return   void -> Bean(返回结果转化为你需要的Bean)  */ public static void executeRequest(List<Map> reqList, String url){  List<HttpParam> list = new ArrayList<HttpParam>();  HttpParam httpParam = new HttpParam();  httpParam.setKey("req");  httpParam.setValue(getValue(reqList));  list.add(httpParam);  String resutl = executeRequest(list,url);  resutl = resutl.substring(8, resutl.length()-1);  System.out.println(resutl);  //Gson gson = new Gson();  //结果Bean respBean = gson.fromJson(resutl, 结果Bean.class);  //return respBean; } /**  * 获取参数的方法(按照代码传参的规则来修改)  * @param list  * @param flag  * @return  */ private static String getValue(List<Map> list) {  StringBuffer data = new StringBuffer();  data.append("{");  if(list != null && list.size() > 0){   for(int i = 0; i < list.size(); i++) {    Map map = list.get(i);    data.append("\"");    data.append(nvlTOString( map.get("key"), "key" ));    data.append("\":\"");    data.append(nvlTOString( map.get("value"), "value" ));    data.append("\"");   }  }  data.append("}");  return data.toString(); } public static String nvlTOString(Object inObject,String defaultString){  String retString = "";  if(inObject!=null){   retString=String.valueOf(inObject).toString();  }else{   retString=defaultString;  }  return retString; } /**  * HttpClient调用接口  * @param list  * @param url  * @return  */ public static String executeRequest(List<HttpParam> list, String url) {  // 响应内容  String result = "";  // 定义http客户端对象--httpClient  HttpClient httpClient = new HttpClient();  // 定义并实例化客户端链接对象-postMethod  PostMethod postMethod = new PostMethod(url);  try {   // 设置http的头   postMethod.setRequestHeader("ContentType",     "application/x-www-form-urlencoded;charset=UTF-8");   // 将表单的值放入postMethod中   postMethod.setRequestBody(convMap(list));   // 定义访问地址的链接状态   int statusCode = 0;   try {    // 客户端请求url数据    statusCode = httpClient.executeMethod(postMethod);   } catch (Exception e) {    e.printStackTrace();   }   System.out.println("statusCode:  " + statusCode + "   DESC: "     + postMethod.getStatusText());   // 请求成功状态-200   if (statusCode == HttpStatus.SC_OK) {    try {     //String charSet =  postMethod.getResponseCharSet();     result = postMethod.getResponseBodyAsString();     //System.out.println("返回结果的编码格式 = " + charSet);     //byte[] bytes = result.getBytes("ISO-8859-1"); //解码     //result = new String(bytes,"UTF-8"); //编码    } catch (IOException e) {     e.printStackTrace();    }   } else {    System.out.println("请求返回状态 = " + statusCode);   }  } catch (Exception e) {   System.out.println(e.getMessage());  } finally {   // 释放链接   postMethod.releaseConnection();   httpClient.getHttpConnectionManager().closeIdleConnections(0);  }  return result; } private static NameValuePair[] convMap(List<HttpParam> paramList) {  // 请求参数  NameValuePair[] data = null;  // 设置请求参数  if (paramList != null) {   data = new NameValuePair[paramList.size()];

   for (int i = 0; i < paramList.size(); i++) {    data[i] = new NameValuePair(paramList.get(i).getKey(),      paramList.get(i).getValue());   }  }  return data; }}/** * HttpClient参数Bean * @author User * */class HttpParam { /**  * 入参KEY  */ private String key; /**  * 入参VALUE  */ private String value; public String getKey() {  return key; } public void setKey(String key) {  this.key = key; } public String getValue() {  return value; } public void setValue(String value) {  this.value = value; } @Override public String toString() {  return "HttpParam [key=" + key + ", value=" + value + "]"; }}

希望对你有帮助,祝你有一个好心情,加油!

若有错误、不全、可优化的点,欢迎纠正与补充!

原创粉丝点击