private static final Log logger = LogFactory.getLog(HttpClientUtil.class);
public static String doPost(String url , Object requestObj) throws Exception{
HttpClient client = new HttpClient();
// logger.debug("请求URL:"+url);
// logger.debug("请求参数:"+(JSONObject.fromObject(requestObj)));
PostMethod postMethod = new PostMethod(url);
postMethod.setRequestHeader(new Header("Content-Type", "application/x-www-form-urlencoded"));
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
NameValuePair[] nameValuePairs = formatParamPost(requestObj);
String response="";
try {
postMethod.setRequestBody(nameValuePairs);
// logger.debug("收到反馈状态:"+postMethod.getStatusLine());
int status = client.executeMethod(postMethod);
if(status == HttpStatus.SC_OK){
response = postMethod.getResponseBodyAsString();
postMethod.getResponseBodyAsString();
// logger.debug("收到反馈报文:"+response);
}else{
logger.error("连接失败");
throw new Exception("连接失败");
}
} catch (Exception e) {
e.printStackTrace();
logger.error("请求远程服务器失败:"+e.getMessage());
throw e;
}finally{
postMethod.releaseConnection();
}
return response;
}
public static NameValuePair[] formatParamPost(Object obj){
JSONObject param = JSONObject.fromObject(obj);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
@SuppressWarnings("unchecked")
Iterator<String> it = param.keys();
while (it.hasNext()) {
String key = (String) it.next();
String value = param.getString(key);
nameValuePairList.add(new NameValuePair(key,value));
}
return (NameValuePair[]) nameValuePairList.toArray(new NameValuePair[nameValuePairList.size()]);
}
public static String doGet(String url ) throws Exception{
HttpClient client = new HttpClient();
logger.debug("请求URL:"+url);
GetMethod getMethod = new GetMethod(url);
getMethod.setRequestHeader(new Header("Content-Type", "application/x-www-form-urlencoded"));
getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
String response="";
try {
logger.debug("收到反馈状态:"+getMethod.getStatusLine());
int status = client.executeMethod(getMethod);
if(status == HttpStatus.SC_OK){
response = getMethod.getResponseBodyAsString();
getMethod.getResponseBodyAsString();
logger.debug("收到反馈报文:"+response);
}else{
logger.error("连接失败");
throw new Exception("连接失败");
}
} catch (Exception e) {
e.printStackTrace();
logger.error("请求远程服务器失败:"+e.getMessage());
throw e;
}finally{
getMethod.releaseConnection();
}
return response;
}
解析json
response = HttpClientUtil.doGet(url);
response = response.replace("null", "\"\"");
jsonObject = JSONObject.fromObject(response);
本文介绍了一个简单的HTTP客户端工具类,包括GET和POST请求的方法实现。该工具类使用HttpClient进行网络请求,并支持传递JSON格式的数据作为请求参数。此外,还展示了如何解析返回的JSON响应。
250

被折叠的 条评论
为什么被折叠?



