CannotinstantiatethetypeHttpClient问题(转)看⾃⼰动⼿写爬⾍,没想到⼀上来就跪了。
⾥⾯提到⽤的jar包是apache的http客户端开源项⽬---HttpClient
就去官⽹下载了⼀个版本4.3
当按书上代码敲时
HttpClient httpclient = new HttpClient();
敲完这句,就给跪了
提⽰Cannot instantiate the type HttpClient,
google 了下,在stackoverflow上⾯说是应该
HttpClient httpclient = new DefaultHttpClient();
这样写,不过得先import org.apache.http.impl.client.DefaultHttpClient;
试了⼀下。。。果然可以,但是后⾯的GetMethod啥的都有,
最后才特么发现从4.×版本后,它的⽤法就变了不能这么使⽤了
给个官⽹⽰例看看就知道咋回事了
package spider;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.hods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class Spider {
public static void main(String[] args) throws Exception{
CloseableHttpClient httpclient = ateDefault();
try{
String url = "www.baidu";
HttpGet httpGet = new HttpGet(url);
System.out.println("executing request " + URI());
ResponseHandler<String> responseHandler = new ResponseHandler<String>(){
public String handleResponse(final HttpResponse response) throws ClientProtocolException,IOException{
下载apache
int status = StatusLine().getStatusCode();
if (status >= 200 && status < 300){
HttpEntity entity = Entity();
return entity !=null ? String(entity) : null;
}else{
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
};
String responseBody = ute(httpGet,responseHandler);
System.out.println("-------------------------------------------");
System.out.println(responseBody);
System.out.println("-------------------------------------------");
}finally{
httpclient.close();
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。