如何设置与Apache HTTP客户端库4.1自定义用户代理?
如何使HTTPClient使用自定义User-Agent头?
以下代码提交空的用户代理。 我错过了什么?
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.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; public class TestHTTP { public static void main(String[] args) throws ClientProtocolException, IOException { HttpGet request = new HttpGet("http://tool.keepmeapi.com/echo"); HttpContext HTTP_CONTEXT = new BasicHttpContext(); HTTP_CONTEXT.setAttribute(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13"); request.setHeader("Referer", "http://www.google.com"); HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request, HTTP_CONTEXT); if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() >= 400) { throw new IOException("Got bad response, error code = " + response.getStatusLine().getStatusCode()); } HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println(EntityUtils.toString(entity)); EntityUtils.consume(entity); } } }
该线
request.setHeader("User-Agent", "MySuperUserAgent");
不见了。 添加并享受。
您还可以设置全局用户代理值而不是每个请求:
String userAgent = "NewUseAgent/1.0"; HttpClient httpClient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgent);
使用httpcomponents 4.3,您应该使用客户端构build器来设置用户代理:
HttpClient httpClient = HttpClients.custom() .setUserAgent("my UserAgent 5.0") .build(); httpClient.execute(new HttpGet("http://www.google.de"));