2010-06-02 75 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()); 
} 

注:有许多有用的方法来操作你的回应。