如何使用 apache http 客户端库 4.1 设置自定义用户代理? [英] How to set custom User-Agent with apache http client library 4.1?

查看:28
本文介绍了如何使用 apache http 客户端库 4.1 设置自定义用户代理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让 HTTPClient 使用自定义 User-Agent 标头?

How to make HTTPClient use custom User-Agent header?

以下代码提交空的用户代理.我错过了什么?

The following code submits empty user-agent. What am I missing?

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);
        }
    }

}

推荐答案

注意:该解决方案适用于使用旧的 httpcomponents 4.2 及之前版本的用户.

Note: The solution is for users using the old httpcomponents 4.2 and before.

线

request.setHeader("User-Agent", "MySuperUserAgent");

不见了.添加它并享受.

is missing. Add it and enjoy.

这篇关于如何使用 apache http 客户端库 4.1 设置自定义用户代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆