2011-07-27 136 views
6

我需要添加具有如下格式的非標準請求標頭:(X-MMP-Params:fs = 640x0)。 我使用了HTTPClient這裏是代碼:如何將請求頭添加到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); 

這是做了正確的方式?

+0

它工作嗎?爲了測試,您可以設置User-Agent頭,並下載顯示服務器檢索的用戶代理的頁面(或創建您自己的PHP頁面)。如果顯示的用戶代理是你設置的,那麼這個方法是有效的。 –

+3

對於那些徘徊於此並思考的人,「好吧,這是正確的方式?!」,答案是肯定的。這工作得很好。 – PFranchise

+0

你是否意識到你[不應該再使用'HttpClient'](http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-客戶);至少不適用於Android項目。 – toKrause

回答

0

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

我個人reccoment嘗試以下列方式

public interface YourUsersApi { 

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

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

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

} 
改造
+0

我沒有看到標題! –