『壹』 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應該怎麼使用

  1. 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.
    */

  2. public class ClientFormLogin {public static void main(String[] args) throws Exception { BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient = HttpClients.custom()
    .setDefaultCookieStore(cookieStore)
    .build();
    try {

  3. 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:");

  4. 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();}

  5. HttpUriRequest login = RequestBuilder.post()
    .setUri(new URI("https://someportal/"))
    .addParameter("IDToken1", "username")
    addParameter("IDToken2", "password")
    .build();CloseableHttpResponse response2 = httpclient.execute(login);

  6. 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();

  7. 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&&params.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;
}