httpclientforjava
『壹』 java中的httpclient4.5应该怎么使用
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.protocol.HTTP;
import org.apache.http.util.EntityUtils;
@SuppressWarnings("deprecation")
public class HttpUtil {
private static final String UTF_8 = HTTP.UTF_8;
public static String post(String url , Map<String , String> params) throws Exception{
DefaultHttpClient client = HttpFactory.createHttpClient();
HttpPost post = new HttpPost(url);
if(params != null ){
List<BasicNameValuePair> lparams = new LinkedList<BasicNameValuePair>();
for (ConcurrentHashMap.Entry<String, String> entry : params.entrySet()) {
if (entry.getValue() != null) {
lparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}else{
lparams.add(new BasicNameValuePair(entry.getKey(), ""));
}
}
HttpEntity entiry = new UrlEncodedFormEntity(lparams, UTF_8);
post.setEntity(entiry);
}
try {
HttpResponse resonse = client.execute(post);
return entityToString(resonse);
} catch (Exception exception) {
throw exception;
} finally {
post.abort();
client.getConnectionManager().shutdown();
}
}
public static String get(String url) throws Exception{
DefaultHttpClient client = HttpFactory.createHttpClient();
HttpGet get = new HttpGet(url);
try {
HttpResponse resonse = client.execute(get);
return entityToString(resonse);
} catch (Exception exception) {
throw exception;
} finally {
get.abort();
client.getConnectionManager().shutdown();
}
}
public static String entityToString(HttpResponse resonse) throws Exception{
HttpEntity entity = resonse.getEntity();
if (entity != null) {
String msg = null;
try {
msg = EntityUtils.toString(entity, UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
int code = resonse.getStatusLine().getStatusCode();
if (code == 200) {
return msg;
} else {
String errerMsg = (msg == null ? null : msg);
throw new Exception("http code:" + code +",error:"+ errerMsg);
}
}
throw new Exception("http entity is null");
}
public static byte[] entityTobyte(HttpResponse resonse) throws Exception {
HttpEntity entity = resonse.getEntity();
if (entity != null) {
byte[] buffer = null;
try {
buffer = EntityUtils.toByteArray(entity);
} catch (IOException e) {
e.printStackTrace();
}
int code = resonse.getStatusLine().getStatusCode();
if (code == 200) {
return buffer;
} else {
String errerMsg = (buffer == null ? null : new String(buffer, UTF_8));
throw new Exception("http code:" + code +",error:"+ errerMsg);
}
}
throw new Exception("http entity is null");
}
}
在官方包中是有例子的:
贴几个给看看 模拟表达登录请求
package org.apache.http.examples.client;
import java.net.URI;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* A example that demonstrates how HttpClient APIs can be used to perform
* form-based logon.
*/
public class ClientFormLogin {
public static void main(String[] args) throws Exception {
BasicCookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
try {
HttpGet httpget = new HttpGet("https://someportal/");
CloseableHttpResponse response1 = httpclient.execute(httpget);
try {
HttpEntity entity = response1.getEntity();
System.out.println("Login form get: " + response1.getStatusLine());
EntityUtils.consume(entity);
System.out.println("Initial set of cookies:");
List<Cookie> cookies = cookieStore.getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
} finally {
response1.close();
}
HttpUriRequest login = RequestBuilder.post()
.setUri(new URI("https://someportal/"))
.addParameter("IDToken1", "username")
.addParameter("IDToken2", "password")
.build();
CloseableHttpResponse response2 = httpclient.execute(login);
try {
HttpEntity entity = response2.getEntity();
System.out.println("Login form get: " + response2.getStatusLine());
EntityUtils.consume(entity);
System.out.println("Post logon cookies:");
List<Cookie> cookies = cookieStore.getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
} finally {
response2.close();
}
} finally {
httpclient.close();
}
}
}
『贰』 js实现java httpclient 功能
为什么不用httpclient模拟这个网页跳转?你这个window.setTimeout('document.getElementById("formxh4t").submit();',3000);含义貌似是提交表单,你模拟表单请求就是了,貌似httpclient没这功能
『叁』 Java中的httpclient4.5应该怎么使用
代码如下:
package org.apache.http.examples.client;
import java.net.URI;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;/**
* A example that demonstrates how HttpClient APIs can be used to perform
* form-based logon.
*/public class ClientFormLogin {public static void main(String[] args) throws Exception { BasicCookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
try {HttpGet httpget = new HttpGet("https://someportal/");
CloseableHttpResponse response1 = httpclient.execute(httpget);
try {HttpEntity entity = response1.getEntity();
System.out.println("Login form get: " + response1.getStatusLine());
EntityUtils.consume(entity);
System.out.println("Initial set of cookies:");List<Cookie> cookies = cookieStore.getCookies();
if (cookies.isEmpty()) {System.out.println("None");} else {for (int i = 0; i < cookies.size(); i++) {System.out.println("- " + cookies.get(i).toString());}} } finally {response1.close();}HttpUriRequest login = RequestBuilder.post()
.setUri(new URI("https://someportal/"))
.addParameter("IDToken1", "username")
addParameter("IDToken2", "password")
.build();CloseableHttpResponse response2 = httpclient.execute(login);try {HttpEntity entity = response2.getEntity();
System.out.println("Login form get: " + response2.getStatusLine());EntityUtils.consume(entity);
System.out.println("Post logon cookies:")
List<Cookie> cookies = cookieStore.getCookies();for (int i = 0; i < cookies.size();
i++) {}finally {response2.close();
finally}
『肆』 如何使用HttpClient包实现JAVA发起HTTP请求
publicclassHttpClientUtil{
publicstaticStringdoGet(Stringurl,Map<String,String>param){
//创建对象
CloseableHttpClienthttpclient=HttpClients.createDefault();
StringresultString="";
CloseableHttpResponseresponse=null;
try{
//创建uri
URIBuilderbuilder=newURIBuilder(url);
if(param!=null){
for(Stringkey:param.keySet()){
builder.addParameter(key,param.get(key));
}
}
URIuri=builder.build();
//创建httpGET请求
HttpGethttpGet=newHttpGet(uri);
//执行请求
response=httpclient.execute(httpGet);
//判断返回状态是否为200
if(response.getStatusLine().getStatusCode()==200){
resultString=EntityUtils.toString(response.getEntity(),"UTF-8");
}
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
if(response!=null){
response.close();
}
httpclient.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
returnresultString;
}
publicstaticStringdoGet(Stringurl){
returndoGet(url,null);
}
publicstaticStringdoPost(Stringurl,Map<String,String>param){
//创建Httpclient对象
CloseableHttpClienthttpClient=HttpClients.createDefault();
CloseableHttpResponseresponse=null;
StringresultString="";
try{
//创建HttpPost请求
HttpPosthttpPost=newHttpPost(url);
//创建参数列表
if(param!=null){
List<NameValuePair>paramList=newArrayList<>();
for(Stringkey:param.keySet()){
paramList.add(newBasicNameValuePair(key,param.get(key)));
}
//模拟表单
UrlEncodedFormEntityentity=newUrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
//执行http请求
response=httpClient.execute(httpPost);
System.out.println(response.getStatusLine());
resultString=EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(resultString);
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
response.close();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
returnresultString;
}
publicstaticStringdoPost(Stringurl){
returndoPost(url,null);
}
publicstaticStringdoPostJson(Stringurl,Stringjson){
//创建Httpclient对象
CloseableHttpClienthttpClient=HttpClients.createDefault();
CloseableHttpResponseresponse=null;
StringresultString="";
try{
//创建HttpPost请求
HttpPosthttpPost=newHttpPost(url);
//创建请求内容
StringEntityentity=newStringEntity(json,ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
//执行http请求
response=httpClient.execute(httpPost);
resultString=EntityUtils.toString(response.getEntity(),"utf-8");
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
response.close();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
returnresultString;
}
}
『伍』 使用java开源工具httpclient怎么使用
使用java开源工具httpClient及jsoup抓取解析网页数据
来源:iteye,原文
今天做项目的时候遇到这样一个需求,需要在网页上展示今日黄历信息,数据格式如下
公历时间:2016年04月11日星期一
农历时间:猴年三月初五
天干地支:丙申年壬辰月癸亥日
宜:求子祈福开光祭祀安床
忌:玉堂(黄道)危日,忌出行
主要包括公历/农历日期,以及忌宜信息的等。但是手里并没有现成的数据可供使用,怎么办呢?革命前辈曾经说过,没有枪,没有炮,敌(wang)人(luo)给我们造!网络上有很多现成的在线万年历应用可供使用,虽然没有现成接口,但是我们可以伸出手来,自己去拿。也就是所谓的数据抓取。
这里介绍两个使用的工具,httpClient以及jsoup,简介如下:
HttpClient是ApacheJakartaCommon下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如ApacheJakarta上很著名的另外两个开源项目Cactus和htmlUnit都使用了HttpClient。
httpClient使用方法如下:
1.创建HttpClient对象。
2.创建请求方法的实例,并指定请求URL。
3.调用HttpClient对象的execute(HttpUriRequestrequest)发送请求,该方法返回一个HttpResponse。
4.调用HttpResponse相关方法获取相应内容。
5.释放连接。
jsoup是一款Java的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作方法来取出和操作数据。
需要更多信息可以参见官网下载地址
httpClient:http://hc.apache.org/httpcomponents-client-5.0.x/index.html
jsoup:http://jsoup.org/
接下来我们直接上代码,这里我们抓取2345在线万年历的数据http://tools.2345.com/rili.htm
首先我们定义一个实体类Almanac来存储黄历数据
Almanac.java1packagecom.likx.picker.util.bean;2
3/**4
*万年历工具实体类5
*
6
*@author溯源blog7
*2016年4月11日8
*/9publicclassAlmanac{10
privateStringsolar;
/*阳历e.g.2016年4月11日星期一*/11
privateStringlunar;
/*阴历e.g.猴年三月初五*/12
privateStringchineseAra;
/*天干地支纪年法e.g.丙申年壬辰月癸亥日*/13
privateStringshould;
/*宜e.g.求子祈福开光祭祀安床*/14
privateStringavoid;
/*忌e.g.玉堂(黄道)危日,忌出行*/1516
publicStringgetSolar(){17
returnsolar;18
}1920
publicvoidsetSolar(Stringdate){21
this.solar=date;22
}2324
publicStringgetLunar(){25
returnlunar;26
}2728
publicvoidsetLunar(Stringlunar){29
this.lunar=lunar;30
}3132
publicStringgetChineseAra(){33
returnchineseAra;34
}3536
publicvoidsetChineseAra(StringchineseAra){37
this.chineseAra=chineseAra;38
}3940
publicStringgetAvoid(){41
returnavoid;42
}4344
publicvoidsetAvoid(Stringavoid){45
this.avoid=avoid;46
}4748
publicStringgetShould(){49
returnshould;50
}5152
publicvoidsetShould(Stringshould){53
this.should=should;54
}5556
publicAlmanac(Stringsolar,Stringlunar,StringchineseAra,Stringshould,57
Stringavoid){58
this.solar=solar;59
this.lunar=lunar;60
this.chineseAra=chineseAra;61
this.should=should;62
this.avoid=avoid;63
}64}
然后是抓取解析的主程序,写程序之前需要在官网下载需要的jar包
AlmanacUtil.javapackagecom.likx.picker.util;importjava.io.IOException;importjava.text.SimpleDateFormat;importjava.util.Calendar;importjava.util.Date;importorg.apache.http.HttpEntity;importorg.apache.http.ParseException;importorg.apache.http.client.ClientProtocolException;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.util.EntityUtils;importorg.jsoup.Jsoup;importorg.jsoup.nodes.Document;importorg.jsoup.nodes.Element;importorg.jsoup.select.Elements;/***<STRONG>类描述</STRONG>:
2345万年历信息爬取工具<p>*
*@version1.0<p>*@author溯源blog*
*<STRONG>创建时间</STRONG>:2016年4月11日下午14:15:44<p>*<STRONG>修改历史</STRONG>:<p>*<pre>*修改人
修改时间
修改内容*---------------
-------------------
-----------------------------------*</pre>*/publicclassAlmanacUtil{
/**
*单例工具类
*/
privateAlmanacUtil(){
}
/**
*获取万年历信息
*@return
*/
publicstaticAlmanacgetAlmanac(){
Stringurl="http://tools.2345.com/rili.htm";
Stringhtml=pickData(url);
Almanacalmanac=analyzeHTMLByString(html);
returnalmanac;
}
/*
*爬取网页信息
*/
privatestaticStringpickData(Stringurl){
CloseableHttpClienthttpclient=HttpClients.createDefault();
try{
HttpGethttpget=newHttpGet(url);
CloseableHttpResponseresponse=httpclient.execute(httpget);
try{
//获取响应实体
HttpEntityentity=response.getEntity();
//打印响应状态
if(entity!=null){
returnEntityUtils.toString(entity);
}
}finally{
response.close();
}
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(ParseExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}finally{
//关闭连接,释放资源
try{
httpclient.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
returnnull;
}
/*
*使用jsoup解析网页信息
*/
(Stringhtml){
StringsolarDate,lunarDate,chineseAra,should,avoid="";
Documentdocument=Jsoup.parse(html);
//公历时间
solarDate=getSolarDate();
//农历时间
ElementeLunarDate=document.getElementById("info_nong");
lunarDate=eLunarDate.child(0).html().substring(1,3)+eLunarDate.html().substring(11);
//天干地支纪年法
ElementeChineseAra=document.getElementById("info_chang");
chineseAra=eChineseAra.text().toString();
//宜
should=getSuggestion(document,"yi");
//忌
avoid=getSuggestion(document,"ji");
Almanacalmanac=newAlmanac(solarDate,lunarDate,chineseAra,should,avoid);
returnalmanac;
}
/*
*获取忌/宜
*/
(Documentdoc,Stringid){
Elementelement=doc.getElementById(id);
Elementselements=element.getElementsByTag("a");
StringBuffersb=newStringBuffer();
for(Elemente:elements){
sb.append(e.text()+"");
}
returnsb.toString();
}
/*
*获取公历时间,用yyyy年MM月dd日EEEE格式表示。
*@returnyyyy年MM月dd日EEEE
*/
(){
Calendarcalendar=Calendar.getInstance();
DatesolarDate=calendar.getTime();
SimpleDateFormatformatter=newSimpleDateFormat("yyyy年MM月dd日EEEE");
returnformatter.format(solarDate);
}}
为了简单明了我把抓取解析抽象成了几个独立的方法,
其中pickData()方法使用httpClient来抓取数据到一个字符串中(就是在网页上点击查看源代码看到的HTML源码),analyzeHTMLByString()方法来解析抓取到的字符串,getSuggestion方法把抓取方法类似的宜忌数据抽象到了一起,另外因为公历时间可以很容易的自己生成就没有在网页上爬取。
然后下面是一个测试类简单测试下效果:AlmanacUtilTest.javapackagecom.likx.picker.util.test;publicclassAlmanacUtilTest{
publicstaticvoidmain(Stringargs[]){
Almanacalmanac=AlmanacUtil.getAlmanac();
System.out.println("公历时间:"+almanac.getSolar());
System.out.println("农历时间:"+almanac.getLunar());
System.out.println("天干地支:"+almanac.getChineseAra());
System.out.println("宜:"+almanac.getShould());
System.out.println("忌:"+almanac.getAvoid());
}}
运行结果如下:
集成到实际项目中效果是这样的:
另外最近博客一直没怎么更新,因为最近考虑到技术氛围的原因,离开了对日外包行业,前往一家互联网公司就职。说一下最近的感受,那就是一个程序员最核心的竞争力不是学会了多少框架,掌握多少种工具(当然这些对于程序员也不可或缺),而是扎实的基础以及快速学习的能力,比如今天这个项目,从对httpClient,jsoup工具一无所知到编写出Demo代码总计大概1个多小时,在之前对于我来说是不可想象的,在技术氛围浓厚的地方快速get技能的感觉,非常好。
当然本例只是一个非常浅显的小例子,网页上内容也很容易抓取,httpClient及jsoup工具更多强大的地方没有体现到,比如httpClient不仅可以发送get请求,而且可以发送post请求,提交表单,传送文件,还比如jsoup最强大的地方在于它支持仿jquery的选择器。本例仅仅使用了最简单的document.getElementById()匹配元素,实际上jsoup的选择器异常强大,可以说它就是java版的jquery,比如这样:Elementslinks=doc.select("a[href]");//awithhrefElementspngs=doc.select("img[src$=.png]");
//imgwithsrcending.pngElementmasthead=doc.select("div.masthead").first();
//divwithclass=mastheadElementsresultLinks=doc.select("h3.r>a");//directaafterh3
『陆』 javahttpclient post请求 x-forwarded-for这个可以设置成其他ip么
目前,要为另一个项目提供接口,接口是用HTTP URL实现的,最初的想法是另一个项目用jQuery post进行请求。
但是,很可能另一个项目是部署在别的机器上,那么就存在跨域问题,而jquery的post请求是不允许跨域的。
这时,就只能够用HttpClient包进行请求了,同时由于请求的URL是HTTPS的,为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程。
写一个SSLClient类,继承至HttpClient。
『柒』 除了HttpClient,Java还有什么类似HttpClient的技术
更直接一点吧,用jdk自带的urlconnection来实现,无需依赖其他库。下边的示例实现了post和get方法。
示例如下:
Java代码
publicclassHttpUtil{
="UTF-8";
publicstaticStringpost(Stringurl,Map<String,String>postParams){
HttpURLConnectioncon=null;
OutputStreamosw=null;
InputStreamins=null;
try{
con=(HttpURLConnection)newURL(url).openConnection();
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
if(null!=postParams){
con.setDoOutput(true);
StringpostParam=encodeParameters(postParams);
byte[]bytes=postParam.getBytes(CHARSET);
con.setRequestProperty("Content-Length",
Integer.toString(bytes.length));
osw=con.getOutputStream();
osw.write(bytes);
osw.flush();
}
intresCode=con.getResponseCode();
if(resCode<400){
ins=con.getInputStream();
}else{
ins=con.getErrorStream();
}
returnreadContent(ins);
}catch(IOExceptione){
}finally{
try{
if(osw!=null){
osw.close();
}
if(ins!=null){
ins.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
returnnull;
}
publicstaticStringget(Stringurl){
HttpURLConnectioncon=null;
OutputStreamosw=null;
InputStreamins=null;
try{
con=(HttpURLConnection)newURL(url).openConnection();
con.setRequestMethod("GET");
intresCode=con.getResponseCode();
if(resCode<400){
ins=con.getInputStream();
}else{
ins=con.getErrorStream();
}
returnreadContent(ins);
}catch(IOExceptione){
}finally{
try{
if(osw!=null){
osw.close();
}
if(ins!=null){
ins.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
returnnull;
}
(InputStreamins)throwsIOException{
StringBuildersb=newStringBuilder();
BufferedReaderbr=newBufferedReader(newInputStreamReader(ins,
HttpUtil.CHARSET));
if(ins!=null){
Stringline;
while((line=br.readLine())!=null){
sb.append(line);
}
}
returnsb.toString();
}
(Map<String,String>postParams){
StringBuilderbuf=newStringBuilder();
if(postParams!=null&&postParams.size()>0){
for(Map.Entry<String,String>tmp:postParams.entrySet()){
try{
buf.append(URLEncoder.encode(tmp.getKey(),CHARSET))
.append("=")
.append(URLEncoder.encode(tmp.getValue(),CHARSET))
.append("&");
}catch(java.io.){
}
}
buf.deleteCharAt(buf.length()-1);
}
returnbuf.toString();
}
}
『捌』 java中运行httpclient,显示出空指针错误,求各位大神帮帮忙
这不是空指针。。。这是找不到HttpEntity类。。是不是你httpclient的jar文件版本不对,或是没配置好?
『玖』 用java写了一个Http client,但向服务器post的时候传中文参数老是乱码,请大侠明示一下
以上的2个方法最好都抄要用上 过滤器只能解决POST请求 ,要处理GET请求就要用
bytes = string.getBytes("iso-8859-1") 得到原始的字节串,再用 string = new String(bytes, "GB2312") 重新得到正确的字符串 。
这个方法,所以最好2个都要写,这样不管是POST还是GET请求就都能解决了。
『拾』 java swing通过httpclient向服务器端发送post请求如何做
/**
*@Description:post请求远程http链接
*@paramurl链接地址
*@parambean实体对象参数
*@paramparams多个字符串参数
*@returnjson
*@throwsException
*/
(Stringurl,Objectbean,String...params)throwsException{
System.err.println(params.length);
HttpClientclient=getHttpClient();
HttpPosthttppost=newHttpPost(url);
MultipartEntityentity=newMultipartEntity();
for(Fieldf:bean.getClass().getDeclaredFields()){
f.setAccessible(true);
if(f.get(bean)!=null&&!"".equals(f.get(bean).toString())){
entity.addPart(f.getName(),newStringBody(f.get(bean).toString(),Charset.forName("UTF-8")));
}
}
for(Fieldf:bean.getClass().getSuperclass().getDeclaredFields()){
f.setAccessible(true);
if(f.get(bean)!=null&&!"".equals(f.get(bean).toString())){
entity.addPart(f.getName(),newStringBody(f.get(bean).toString(),Charset.forName("UTF-8")));
}
}
if(params!=null&¶ms.length!=0){
Map<String,Object>paramsMap=MapTool.getParamMap(params);
for(StringparamName:paramsMap.keySet()){
entity.addPart(paramName,newStringBody((String)paramsMap.get(paramName),Charset.forName("UTF-8")));
}
}
httppost.setEntity(entity);
Stringresp=null;
try{
HttpResponseresponse=client.execute(httppost);
HttpEntityresEntity=response.getEntity();
if(resEntity!=null){
resp=EntityUtils.toString(resEntity,"UTF-8");
}
if(resEntity!=null){
EntityUtils.consume(resEntity);
}
}finally{
client.getConnectionManager().shutdown();
}
returnresp;
}