How to set custom User-Agent with apache http client library 4.1?

前端 未结 3 574
深忆病人
深忆病人 2020-12-08 02:03

How to make HTTPClient use custom User-Agent header?

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

import java.io.IOException;

imp         


        
相关标签:
3条回答
  • 2020-12-08 02:41

    The line

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

    is missing. Add it and enjoy.

    0 讨论(0)
  • 2020-12-08 02:42

    With httpcomponents 4.3 you should use the client builder to set the user agent:

    HttpClient httpClient = HttpClients.custom()
                                .setUserAgent("my UserAgent 5.0")
                                .build();
    
    httpClient.execute(new HttpGet("http://www.google.de"));
    
    0 讨论(0)
  • 2020-12-08 02:44

    You can also set a global user agent value instead of per request:

    String userAgent = "NewUseAgent/1.0";
    HttpClient httpClient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgent);
    
    0 讨论(0)
提交回复
热议问题