java使用common-httpclient包实现post请求方法示例
前言
项目中需要请求第三方接口,而且要求请求参数数据为json类型的。本来首先使用的是httpclient的jar包,但是因为项目中已经使用了common-httpclient的jar包,引起了冲突,所以不得不使用common-httpclient来实现。
示例代码:
importjava.io.BufferedReader;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.net.URL;
importjava.net.URLConnection;
importjava.util.List;
importjava.util.Map;
importjava.util.zip.GZIPInputStream;
importorg.apache.commons.httpclient.HttpClient;
importorg.apache.commons.httpclient.HttpMethod;
importorg.apache.commons.httpclient.NameValuePair;
importorg.apache.commons.httpclient.methods.GetMethod;
importorg.apache.commons.httpclient.methods.PostMethod;
importorg.apache.commons.httpclient.methods.RequestEntity;
importorg.apache.commons.httpclient.methods.StringRequestEntity;
importorg.apache.commons.io.IOUtils;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
publicclassHTTPUtils{
privatestaticLoggerlogger=LoggerFactory.getLogger(HTTPUtils.class);
/**
*post请求
*@paramurl
*@paramjson
*@return
*/
publicstaticStringpostJosnContent(Stringurl,StringJson)throwsException{
//HttpPostmethod=newHttpPost(url);
//DefaultHttpClienthttpClient=newDefaultHttpClient();
//Stringret=null;
//try{
//StringEntityentity=newStringEntity(Json,"UTF-8");//解决中文乱码问题
//entity.setContentEncoding("UTF-8");
//entity.setContentType("application/json");
//method.setEntity(entity);
//HttpResponseresult=httpClient.execute(method);
//ret=EntityUtils.toString(result.getEntity());
//}catch(Exceptione){
//throwe;
//}finally{
//method.releaseConnection();
//}
//returnret;
logger.error("请求接口参数:"+Json);
PostMethodmethod=newPostMethod(url);
HttpClienthttpClient=newHttpClient();
try{
RequestEntityentity=newStringRequestEntity(Json,"application/json","UTF-8");
method.setRequestEntity(entity);
httpClient.executeMethod(method);
logger.error("请求接口路径url:"+method.getURI().toString());
InputStreamin=method.getResponseBodyAsStream();
//下面将stream转换为String
StringBuffersb=newStringBuffer();
InputStreamReaderisr=newInputStreamReader(in,"UTF-8");
char[]b=newchar[4096];
for(intn;(n=isr.read(b))!=-1;){
sb.append(newString(b,0,n));
}
StringreturnStr=sb.toString();
returnreturnStr;
}catch(Exceptione){
e.printStackTrace();
throwe;
}finally{
method.releaseConnection();
}
}
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。