您的位置:首页 > 编程语言 > Java开发

Java post 请求

2015-08-13 14:46 751 查看
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.PostMethod;

public class Dopost {
public String callHttpPost(String url,NameValuePair[] postData){
HttpClient httpclient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
try{
postMethod.addParameters(postData);
postMethod.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
int statusCode = httpclient.executeMethod(postMethod);
if(statusCode == HttpStatus.SC_MOVED_TEMPORARILY  ||
statusCode == HttpStatus.SC_MOVED_TEMPORARILY){
Header locationHeader = postMethod.getResponseHeader("Location");
String location = null;
if(locationHeader != null){
location = locationHeader.getValue();
}
postMethod = new PostMethod(location);
postMethod.setRequestBody(postData);
postMethod.getParams().setParameter("http.protocol.cookie-policy",CookiePolicy.BROWSER_COMPATIBILITY);
int statusCode1 = httpclient.executeMethod(postMethod);
if(statusCode1 != HttpStatus.SC_OK){
return "postError01:重定向访问没有成功!";
}
}
if(statusCode != HttpStatus.SC_OK){
return "postError02:访问没有成功!";
}
InputStream responseBody = postMethod.getResponseBodyAsStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(responseBody,"utf-8"));
String line = reader.readLine();
String repose="";
while(line != null){
repose+=new String(line.getBytes());
line = reader.readLine();
}
return repose;
}
catch (HttpException e) {
return "postError03:"+e;
}
catch (IOException e) {
return "postError04:"+e;
}finally{
postMethod.releaseConnection();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: