【问题标题】:How to add request header to HttpClient request?如何将请求标头添加到 HttpClient 请求?
【发布时间】:2011-10-14 17:13:53
【问题描述】:

我需要添加格式如下的非标准请求标头:(X-MMP-Params: fs=640x0)。 我在这里使用 HTTPClient 是代码:

HttpClient client = new DefaultHttpClient();  
String getURL = "http://example.com";
HttpGet get = new HttpGet(getURL);
get.setHeader("X-MMP-Params","fs=640x0"); // I set my request header right here
HttpResponse responseGet = client.execute(get);  

这是正确的方法吗?

【问题讨论】:

  • 有效吗?要进行测试,您可以设置 User-Agent 标头,并下载显示服务器检索的用户代理的页面(或制作您自己的 PHP 页面)。如果显示的用户代理是您设置的,那么此方法有效。
  • 对于那些徘徊于此并认为“嗯,这是正确的方法吗?!”的人,答案是肯定的。这工作得很好。
  • 你知道你shouldn't use HttpClient anymore;至少不适用于 Android 项目。

标签: android http-headers


【解决方案1】:

get 请求是用 HttpGet 发出的:

public static InputStream getInputStreamFromUrl(String url) {
  InputStream content = null;
  try {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(url));
    content = response.getEntity().getContent();
  } catch (Exception e) {
    Log.("[GET REQUEST]", "Network exception", e);
  }
    return content;
}

POST 请求是用 HttpPost:

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
} 

我个人建议尝试 Retrofit 如下方式

public interface YourUsersApi {

   //You can use rx.java for sophisticated composition of requests 
   @GET("/users/{user}")
   public Observable<SomeUserModel> fetchUser(@Path("user") String user);

   //or you can just get your model if you use json api
   @GET("/users/{user}")
   public SomeUserModel fetchUser(@Path("user") String user);

   //or if there are some special cases you can process your response manually 
   @GET("/users/{user}")
   public Response fetchUser(@Path("user") String user);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多