1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStream; 4 import java.io.InputStreamReader; 5 6 7 8 import org.apache.commons.httpclient.Header; 9 import org.apache.commons.httpclient.HttpClient; 10 import org.apache.commons.httpclient.HttpException; 11 import org.apache.commons.httpclient.HttpStatus; 12 import org.apache.commons.httpclient.NameValuePair; 13 import org.apache.commons.httpclient.cookie.CookiePolicy; 14 import org.apache.commons.httpclient.methods.PostMethod; 15 16 public class Dopost { 17 public String callHttpPost(String url,NameValuePair[] postData){ 18 HttpClient httpclient = new HttpClient(); 19 PostMethod postMethod = new PostMethod(url); 20 try{ 21 postMethod.addParameters(postData); 22 postMethod.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY); 23 int statusCode = httpclient.executeMethod(postMethod); 24 if(statusCode == HttpStatus.SC_MOVED_TEMPORARILY || 25 statusCode == HttpStatus.SC_MOVED_TEMPORARILY){ 26 Header locationHeader = postMethod.getResponseHeader("Location"); 27 String location = null; 28 if(locationHeader != null){ 29 location = locationHeader.getValue(); 30 } 31 postMethod = new PostMethod(location); 32 postMethod.setRequestBody(postData); 33 postMethod.getParams().setParameter("http.protocol.cookie-policy",CookiePolicy.BROWSER_COMPATIBILITY); 34 int statusCode1 = httpclient.executeMethod(postMethod); 35 if(statusCode1 != HttpStatus.SC_OK){ 36 return "postError01:重定向访问没有成功!"; 37 } 38 } 39 if(statusCode != HttpStatus.SC_OK){ 40 return "postError02:访问没有成功!"; 41 } 42 InputStream responseBody = postMethod.getResponseBodyAsStream(); 43 BufferedReader reader = new BufferedReader(new InputStreamReader(responseBody,"utf-8")); 44 String line = reader.readLine(); 45 String repose=""; 46 while(line != null){ 47 repose+=new String(line.getBytes()); 48 line = reader.readLine(); 49 } 50 return repose; 51 } 52 catch (HttpException e) { 53 return "postError03:"+e; 54 } 55 catch (IOException e) { 56 return "postError04:"+e; 57 }finally{ 58 postMethod.releaseConnection(); 59 } 60 } 61 }