服务热线
0574-55011290
packagecom.platform.util.common;importjava.io.IOException;importjava.io.UnsupportedEncodingException;importjava.util.ArrayList;importjava.util.List;importjava.util.Map;importjava.util.Set;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.NameValuePair;importorg.apache.http.ParseException;importorg.apache.http.client.ClientProtocolException;importorg.apache.http.client.entity.UrlEncodedFormEntity;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.client.methods.HttpUriRequest;importorg.apache.http.impl.client.DefaultHttpClient;importorg.apache.http.message.BasicNameValuePair;importorg.apache.http.protocol.HTTP;importorg.apache.http.util.EntityUtils;importorg.apache.log4j.Logger;/*** * ============================================ * 功能描述:发送POST/GET请求 ============================================*/ public classHttpXmlClient {private static Logger log = Logger.getLogger(HttpXmlClient.class);public static String post(String url, Mapparams) { DefaultHttpClient httpclient= newDefaultHttpClient(); String body= null; log.info("create httppost:" +url); HttpPost post=postForm(url, params); body=invoke(httpclient, post); httpclient.getConnectionManager().shutdown();returnbody; }public staticString get(String url) { DefaultHttpClient httpclient= newDefaultHttpClient(); String body= null; log.info("create httppost:" +url); HttpGet get= newHttpGet(url); body=invoke(httpclient, get); httpclient.getConnectionManager().shutdown();returnbody; }private staticString invoke(DefaultHttpClient httpclient, HttpUriRequest httpost) { HttpResponse response=sendRequest(httpclient, httpost); String body=paseResponse(response);returnbody; }private staticString paseResponse(HttpResponse response) { log.info("get response from http server.."); HttpEntity entity=response.getEntity(); log.info("response status: " +response.getStatusLine()); String charset=EntityUtils.getContentCharSet(entity); log.info(charset); String body= null;try{ body=EntityUtils.toString(entity); log.info(body); }catch(ParseException e) { e.printStackTrace(); }catch(IOException e) { e.printStackTrace(); }returnbody; }private staticHttpResponse sendRequest(DefaultHttpClient httpclient, HttpUriRequest httpost) { log.info("execute post..."); HttpResponse response= null;try{ response=httpclient.execute(httpost); }catch(ClientProtocolException e) { e.printStackTrace(); }catch(IOException e) { e.printStackTrace(); }returnresponse; }private static HttpPost postForm(String url, Mapparams){ HttpPost httpost= newHttpPost(url); List nvps = new ArrayList (); Set keySet =params.keySet();for(String key : keySet) { nvps.add(newBasicNameValuePair(key, params.get(key))); }try{ log.info("set utf-8 form entity to httppost"); httpost.setEntity(newUrlEncodedFormEntity(nvps, HTTP.UTF_8)); }catch(UnsupportedEncodingException e) { e.printStackTrace(); }returnhttpost; } }
|
|||||
>> 相关文章 | |||||