2010-06-02 116 views
115

我有一個HTTP GET請求,我試圖發送。我嘗試通過首先創建一個BasicHttpParams對象並將參數添加到該對象,然後在我的HttpGet對象上調用setParams(basicHttpParms)來嘗試向此請求添加參數。此方法失敗。但是,如果我手動將我的參數添加到我的URL(即追加?param1=value1&param2=value2)它會成功。如何在Android中向HTTP GET請求添加參數?

我知道我在這裏失去了一些東西,任何幫助將不勝感激。

+1

對於GET請求,第二種方法是添加參數的正確方法。我期望第一種方法是用於POST方法。 – 2010-06-02 15:56:32

回答

223

我使用NameValuePair和URLEncodedUtils列表來創建我想要的url字符串。

protected String addLocationToUrl(String url){ 
    if(!url.endsWith("?")) 
     url += "?"; 

    List<NameValuePair> params = new LinkedList<NameValuePair>(); 

    if (lat != 0.0 && lon != 0.0){ 
     params.add(new BasicNameValuePair("lat", String.valueOf(lat))); 
     params.add(new BasicNameValuePair("lon", String.valueOf(lon))); 
    } 

    if (address != null && address.getPostalCode() != null) 
     params.add(new BasicNameValuePair("postalCode", address.getPostalCode())); 
    if (address != null && address.getCountryCode() != null) 
     params.add(new BasicNameValuePair("country",address.getCountryCode())); 

    params.add(new BasicNameValuePair("user", agent.uniqueId)); 

    String paramString = URLEncodedUtils.format(params, "utf-8"); 

    url += paramString; 
    return url; 
} 
+0

我同意。我已經回去改變了這個方法,因爲這個方法對於大量的參數是有意義的。第一個被接受的答案仍然可以正常工作,但對於大量參數可能會造成混淆。 – groomsy 2011-07-11 13:55:00

+0

@Brian Griffey感謝您的好解決方案。但我有一點不同的格式來傳遞參數,任何人都可以幫我傳遞這個參數..? 在這種情況下如何傳遞參數? 數據=「{ 「憑證」:{ 「accesToken」: 「668f514678c7e7f5e71a07044935d94c」, 「ACK」: 「cf3bb509623a8e8fc032a08098d9f7b3」 }, 「restin的」:{ 「用戶id」:4, 「listId」: 5613 } }; – 2012-09-21 12:38:00

+2

正確是絕對的,沒有升級:)。 很好的答案,多種原因。 – sschrass 2012-10-12 00:34:57

27

方法

setParams() 

httpget.getParams().setParameter("http.socket.timeout", new Integer(5000)); 

只增加HttpProtocol參數。

要執行HTTPGET您應將參數追加到URL手動

HttpGet myGet = new HttpGet("http://foo.com/someservlet?param1=foo&param2=bar"); 

或使用POST請求 GET和POST請求之間的區別進行解釋here,如果你有興趣

+1

謝謝你的幫助。我認爲可能有一種更有效的方法來向GET請求添加參數。 – groomsy 2010-06-02 16:29:21

91

要使用get參數構建uri,Uri.Builder提供了更有效的方法。

Uri uri = new Uri.Builder() 
    .scheme("http") 
    .authority("foo.com") 
    .path("someservlet") 
    .appendQueryParameter("param1", foo) 
    .appendQueryParameter("param2", bar) 
    .build(); 
+1

太糟糕了,它無法處理端口號。否則很好的答案。 – 2011-05-16 18:41:41

+37

'Uri.Builder b = Uri.parse(「http://www.site.com:1234」).buildUpon();'應該可以工作 – Merlin 2011-07-29 11:24:21

+0

也無法處理文件參數 – siamii 2011-07-31 04:40:06

8
List<NameValuePair> params = new ArrayList<NameValuePair>(); 
params.add(new BasicNameValuePair("param1","value1"); 

String query = URLEncodedUtils.format(params, "utf-8"); 

URI url = URIUtils.createURI(scheme, userInfo, authority, port, path, query, fragment); //can be null 
HttpGet httpGet = new HttpGet(url); 

URI javadoc

注:url = new URI(...)是越野車

28

作爲HttpComponents4.2+有一個新的類URIBuilder,它提供了用於產生的URI方便的方法。

您可以使用直接從字符串URL創建URI:

List<NameValuePair> listOfParameters = ...; 

URI uri = new URIBuilder("http://example.com:8080/path/to/resource?mandatoryParam=someValue") 
    .addParameter("firstParam", firstVal) 
    .addParameter("secondParam", secondVal) 
    .addParameters(listOfParameters) 
    .build(); 

否則,您可以顯式指定所有參數:

URI uri = new URIBuilder() 
    .setScheme("http") 
    .setHost("example.com") 
    .setPort(8080) 
    .setPath("/path/to/resource") 
    .addParameter("mandatoryParam", "someValue") 
    .addParameter("firstParam", firstVal) 
    .addParameter("secondParam", secondVal) 
    .addParameters(listOfParameters) 
    .build(); 

一旦你創建URI對象,那麼你只是單純的需要創建HttpGet對象並執行它:

//create GET request 
HttpGet httpGet = new HttpGet(uri); 
//perform request 
httpClient.execute(httpGet ...//additional parameters, handle response etc. 
+1

這應該是最好的答案,我不知道選定的人有200個upvotes,這個只有20個。 – 2016-04-15 07:57:14

4
HttpClient client = new DefaultHttpClient(); 

    Uri.Builder builder = Uri.parse(url).buildUpon(); 

    for (String name : params.keySet()) { 
     builder.appendQueryParameter(name, params.get(name).toString()); 
    } 

    url = builder.build().toString(); 
    HttpGet request = new HttpGet(url); 
    HttpResponse response = client.execute(request); 
    return EntityUtils.toString(response.getEntity(), "UTF-8"); 
0
class Searchsync extends AsyncTask<String, String, String> { 

    @Override 
    protected String doInBackground(String... params) { 

     HttpClient httpClient = new DefaultHttpClient();/*write your url in Urls.SENDMOVIE_REQUEST_URL; */ 
     url = Urls.SENDMOVIE_REQUEST_URL; 

     url = url + "/id:" + m; 
     HttpGet httpGet = new HttpGet(url); 

     try { 
      // httpGet.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

      // httpGet.setEntity(new StringEntity(json.toString())); 
      HttpResponse response = httpClient.execute(httpGet); 
      HttpEntity resEntity = response.getEntity(); 

      if (resEntity != null) { 

       String responseStr = EntityUtils.toString(resEntity).trim(); 

       Log.d("Response from PHP server", "Response: " 
         + responseStr); 
       Intent i = new Intent(getApplicationContext(), 
         MovieFoundActivity.class); 
       i.putExtra("ifoundmovie", responseStr); 
       startActivity(i); 

      } 
     } catch (UnsupportedEncodingException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     return null; 
    }//enter code here 

} 
0

如果你有固定URL我建議使用簡體http-request建的Apache HTTP。

你可以建立客戶端如下:

private filan static HttpRequest<YourResponseType> httpRequest = 
        HttpRequestBuilder.createGet(yourUri,YourResponseType) 
        .build(); 

public void send(){ 
    ResponseHendler<YourResponseType> rh = 
     httpRequest.execute(param1, value1, param2, value2); 

    handler.ifSuccess(this::whenSuccess).otherwise(this::whenNotSuccess); 
} 

public void whenSuccess(ResponseHendler<YourResponseType> rh){ 
    rh.ifHasContent(content -> // your code); 
} 

public void whenSuccess(ResponseHendler<YourResponseType> rh){ 
    LOGGER.error("Status code: " + rh.getStatusCode() + ", Error msg: " + rh.getErrorText()); 
} 

注:有許多有用的方法來操作你的迴應。