如何在Android中向HTTP GET请求添加参数?

时间:2010-06-02 15:50:03

标签: java android http-get

我正在尝试发送HTTP GET请求。我尝试将参数添加到此请求中,首先创建一个BasicHttpParams对象并将参数添加到该对象,然后在setParams( basicHttpParms )对象上调用HttpGet。此方法失败。但是如果我手动将我的参数添加到我的URL(即附加?param1=value1&param2=value2),它就会成功。

我知道我在这里遗漏了一些东西,非常感谢任何帮助。

7 个答案:

答案 0 :(得分:224)

我使用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;
}

答案 1 :(得分:94)

使用get参数构建uri,Uri.Builder提供了一种更有效的方法。

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

答案 2 :(得分:30)

HttpComponents 4.2+开始,有一个新类URIBuilder,它提供了生成URI的便捷方式。

您可以直接从String URL使用create 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.

答案 3 :(得分:27)

方法

setParams() 

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

仅添加HttpProtocol参数。

要执行httpGet,您应该手动将参数附加到网址

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

或使用发布请求 如果您有兴趣,可以解释获取和发布请求之间的差异here

答案 4 :(得分: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(...)是错误的

答案 5 :(得分: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");

答案 6 :(得分:0)

如果您有URL常数,我建议您使用基于apache http的简化http-request

您可以按照以下方式构建客户端:

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());
}

注意:有许多有用的方法可以操纵您的回复。