1 import com.dadi.saas.util.HTTPUtils;
2 import org.apache.commons.httpclient.Header;
3 import org.apache.commons.httpclient.HttpClient;
4 import org.apache.commons.httpclient.HttpStatus;
5 import org.apache.commons.httpclient.NameValuePair;
6 import org.apache.commons.httpclient.methods.PostMethod;
7
8 import java.io.IOException;
9 import java.util.HashMap;
10 import java.util.Iterator;
11 import java.util.Map;
12
13
14 /**
15 * @author wdsy
16 * @date 2017-06-21
17 */
18
19 public class HttpClientTest {
20
21 public String getPostResponse(String url, Map<String, String> parmMap ) throws IOException {
22 {
23 String result = "";
24 PostMethod post = new PostMethod(url);
25 HttpClient client = new HttpClient();
26 Iterator it = parmMap.entrySet().iterator();
27 NameValuePair[] param = new NameValuePair[parmMap.size()];
28 int i = 0;
29 while (it.hasNext()) {
30 Map.Entry parmEntry = (Map.Entry) it.next();
31 param[i++] = new NameValuePair((String) parmEntry.getKey(), (String) parmEntry.getValue());
32 }
33
34
35 post.setRequestBody(param);
36 try {
37 int statusCode = client.executeMethod(post);
38
39 if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
40 Header locationHeader = post.getResponseHeader("location");
41 String location = "";
42 if (locationHeader != null) {
43 location = locationHeader.getValue();
44 result = this.getPostResponse(location, parmMap);//用跳转后的页面重新请求�??
45 }
46 } else if (statusCode == HttpStatus.SC_OK) {
47 result = post.getResponseBodyAsString();
48 }
49 } catch (IOException ex) {
50 } finally {
51 post.releaseConnection();
52 }
53 return result;
54 }
55 }
56
57 public static void main(String[] args) throws IOException {
58 Map<String, String> map = new HashMap<String, String>();
59 map.put("param1", "xxxx");
60 map.put("param2", "xxxxx");
61 map.put("param3", "xxxxx");
62 Iterator it = map.entrySet().iterator();
63 NameValuePair[] param = new NameValuePair[map.size()];
64 int i = 0;
65 String z =new HttpClientTest().getPostResponse("http://xxxx.xx.xx.xx:xxxx/xx/xx/xx.do?", map);
66 System.out.println(z);
67 }
68 }