import com.dadi.saas.util.HTTPUtils;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod; import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; /**
* @author wdsy
* @date 2017-06-21
*/ public class HttpClientTest { public String getPostResponse(String url, Map<String, String> parmMap ) throws IOException {
{
String result = "";
PostMethod post = new PostMethod(url);
HttpClient client = new HttpClient();
Iterator it = parmMap.entrySet().iterator();
NameValuePair[] param = new NameValuePair[parmMap.size()];
int i = 0;
while (it.hasNext()) {
Map.Entry parmEntry = (Map.Entry) it.next();
param[i++] = new NameValuePair((String) parmEntry.getKey(), (String) parmEntry.getValue());
} post.setRequestBody(param);
try {
int statusCode = client.executeMethod(post); if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
Header locationHeader = post.getResponseHeader("location");
String location = "";
if (locationHeader != null) {
location = locationHeader.getValue();
result = this.getPostResponse(location, parmMap);//用跳转后的页面重新请求�??
}
} else if (statusCode == HttpStatus.SC_OK) {
result = post.getResponseBodyAsString();
}
} catch (IOException ex) {
} finally {
post.releaseConnection();
}
return result;
}
} public static void main(String[] args) throws IOException {
Map<String, String> map = new HashMap<String, String>();
map.put("param1", "xxxx");
map.put("param2", "xxxxx");
map.put("param3", "xxxxx");
Iterator it = map.entrySet().iterator();
NameValuePair[] param = new NameValuePair[map.size()];
int i = 0;
String z =new HttpClientTest().getPostResponse("http://xxxx.xx.xx.xx:xxxx/xx/xx/xx.do?", map);
System.out.println(z);
}
}
pom:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8-beta5</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>