httpcomponents-client-4.3.1 请求百度首页失败

jdgdf566 2013-11-09 10:04:48


import java.util.*;
//post and upload
import java.io.*;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
//cookie and session
import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
//get
import org.apache.http.client.methods.HttpGet;
//post
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;

/**
*
*/
public class HttpRequest {

private String urlString = null;
private int timeOut = 1000*10;
private HashMap<String, String> headerDatasMap = new HashMap<>();
private List<String[]> postDatasList = new ArrayList<>();
private List<String[]> uploadFilesList = new ArrayList<>();
//
private CloseableHttpClient httpclient = null;
private HttpPost httpPost = null;
private HttpGet httpGet = null;
public CookieStore cookieStore = null;
private HttpClientContext localContext = null;
private HttpEntity httpEntity = null;
public CloseableHttpResponse httpResponse = null;
public HttpEntity responseHttpEntity = null;

public HttpRequest(String urlString) {
this.urlString = urlString;
//
this.setHeader("Accept", "text/html, application/xhtml+xml, */*");
this.setHeader("Accept-Language", "zh-CN");
this.setHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)");

}

/**
* after executing...
*/
public String getRequestLine() {
if (this.httpGet != null) {
return this.httpGet.getRequestLine().toString();
} else {
return this.httpPost.getRequestLine().toString();
}
}

public void setHeader(String $name, String $value) {
this.headerDatasMap.put($name, $value);
}

public void setTimeOut(int millionSeconds) {
this.timeOut = millionSeconds;
}

public void addPostData(String name, String value) {
String pair[] = {name, value};
this.postDatasList.add(pair);
}

/**
*
* @param name fieldname
*/
public void addUploadFile(String name, String pathName, String rename) throws Exception {
String fileinfo[] = {name, pathName, rename};
this.uploadFilesList.add(fileinfo);
}

private void prepare() throws Exception {
this.httpclient = HttpClients.createDefault();
/**
* 设置上下文:localContext
*/
//cookie and session
this.cookieStore = new BasicCookieStore();
this.localContext = HttpClientContext.create();
this.localContext.setCookieStore(this.cookieStore);
//超时、跳转等
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
requestConfigBuilder.setConnectTimeout(this.timeOut);
requestConfigBuilder.setConnectionRequestTimeout(this.timeOut);
requestConfigBuilder.setSocketTimeout(this.timeOut);
requestConfigBuilder.setRedirectsEnabled(false);
this.localContext.setRequestConfig(requestConfigBuilder.build());
/**
* 创建Method
*/
if (this.httpGet != null) {
this.httpGet = new HttpGet(this.urlString);
//headerdata
this.prepareHeaders(this.httpGet);
} else {
this.httpPost = new HttpPost(this.urlString);
//headerdata
this.prepareHeaders(this.httpPost);
//
this.preparePostDatasAndUploadFiles();
this.httpPost.setEntity(this.httpEntity);
}
}

private void prepareHeaders(HttpRequestBase httpRequest) {
Set set = this.headerDatasMap.keySet();
Iterator it = set.iterator();
String key;
while (it.hasNext()) {
key = (String) it.next();
httpRequest.setHeader(key, this.headerDatasMap.get(key));
}
}

private void preparePostDatasAndUploadFiles() {
//multipart/form-data
if (this.uploadFilesList.size() > 0) {//uploadFiles
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.STRICT) /**
* .setCharset(Charset.defaultCharset())
*/
;
for (int i = 0; i < this.uploadFilesList.size(); i++) {
String[] files = uploadFilesList.get(i);
multipartEntityBuilder.addBinaryBody(files[0], new File(files[1]), ContentType.DEFAULT_BINARY, files[2]);
}
//postData
for (int i = 0; i < postDatasList.size(); i++) {
String[] strings = postDatasList.get(i);
multipartEntityBuilder.addTextBody(strings[0], strings[1], ContentType.DEFAULT_TEXT);
}
//
this.httpEntity = multipartEntityBuilder.build();
return;
}
//application/x-www-form-urlencoded
if (this.postDatasList.size() > 0) {
List<NameValuePair> nameValuePairs = new ArrayList<>();
//
for (int i = 0; i < postDatasList.size(); i++) {
String[] strings = postDatasList.get(i);
nameValuePairs.add(new BasicNameValuePair(strings[0], strings[1]));
}
//
this.httpEntity = new UrlEncodedFormEntity(nameValuePairs, Consts.UTF_8);
}
}

/**
* execute
*/
public void execute() throws Exception {
if (this.httpclient == null) {
this.prepare();
}
//
if (this.httpGet != null) {
this.httpResponse = this.httpclient.execute(this.httpGet, this.localContext);
} else {
this.httpResponse = this.httpclient.execute(this.httpPost, this.localContext);
}

this.responseHttpEntity = this.httpResponse.getEntity();
}
}

主类:

public class NewMain {
public static void main(String[] args) throws Exception {
/**
* todo
*/
HttpRequest httpClient = new HttpRequest("http://www.baidu.com/");
//HttpRequest httpClient = new HttpRequest("http://localhost/phpinfo.php");
httpClient.execute();

//通过这个输入流可以打印:
httpClient.responseHttpEntity.getContent()
}
}

请求其它网址可以,独百度不行,返回的是:

<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx/1.2.4</center>
</body>
</html>
...全文
193 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
阳哥说全栈 2014-11-19
  • 打赏
  • 举报
回复
setRedirectsEnabled(true)

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧