HttpClient发送get和post请求
且看代码:
import java.io.IOException; import java.io.UnsupportedEncodingException; import javax.xml.ws.Response; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.log4j.Logger; public class HttpUtils_test { static Logger log=Logger.getLogger(HttpUtils_test.class); public static HttpClient httpClient=null; public static HttpClient getInstance(){ if (httpClient==null) { httpClient=new HttpClient(); } return httpClient; } public static void disconnect(){ httpClient=null; } /** * 功能:发送post请求,获取返回报文返回值 * @throws IOException * @throws Exception * @return String 返回的状态码 * * */ public static void doPost(String Url,NameValuePair[] data) throws Exception{ try { HttpClient http=HttpUtils_test.getInstance(); PostMethod post=new PostMethod(Url); post.setRequestBody(data); int status=http.executeMethod(post); System.out.println(status); //判断重定向 if(status==HttpStatus.SC_MOVED_PERMANENTLY||status==HttpStatus.SC_TEMPORARY_REDIRECT||status==HttpStatus.SC_SEE_OTHER ||status==HttpStatus.SC_MOVED_TEMPORARILY){ String locationHeder=post.getResponseHeader("location").getValue(); if (locationHeder!=null) { log.info("The page was redicted to"+" "+locationHeder); doPost(locationHeder, data); }else{ log.info("Location field value is null"); } }else{ log.info(post.getResponseBodyAsString()); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } /** * * 功能:发送Get请求,会的返回值 * @param Url 地址 * */ public static void doget(String Url) throws Exception{ try { GetMethod get=new GetMethod(Url); int status=HttpUtils_test.getInstance().executeMethod(get); System.out.println(status); //判断重定向 if(status==HttpStatus.SC_MOVED_PERMANENTLY||status==HttpStatus.SC_TEMPORARY_REDIRECT||status==HttpStatus.SC_SEE_OTHER ||status==HttpStatus.SC_MOVED_TEMPORARILY){ String locationHeder=get.getResponseHeader("location").getValue(); if (locationHeder!=null) { log.info("The page was redicted to"+" "+locationHeder); } log.info("Location field value is null"); }else{ log.info(get.getResponseBodyAsString()); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }

浙公网安备 33010602011771号