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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2959316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:56:26  来源:igfitidea点击:

How to add parameters to a HTTP GET request in Android?

javaandroidhttp-get

提问by groomsy

I have a HTTP GET request that I am attempting to send. I tried adding the parameters to this request by first creating a BasicHttpParamsobject and adding the parameters to that object, then calling setParams( basicHttpParms )on my HttpGetobject. This method fails. But if I manually add my parameters to my URL (i.e. append ?param1=value1&param2=value2) it succeeds.

我有一个试图发送的 HTTP GET 请求。我尝试通过首先创建一个BasicHttpParams对象并将参数添加到该对象,然后调用setParams( basicHttpParms )我的HttpGet对象来向该请求添加参数。这个方法失败了。但是如果我手动将我的参数添加到我的 URL(即 append ?param1=value1&param2=value2)它会成功。

I know I'm missing something here and any help would be greatly appreciated.

我知道我在这里遗漏了一些东西,任何帮助将不胜感激。

采纳答案by Brian Griffey

I use a List of NameValuePair and URLEncodedUtils to create the url string I want.

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

回答by n3utrino

The method

方法

setParams() 

like

喜欢

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

only adds HttpProtocol parameters.

只添加 HttpProtocol 参数。

To execute the httpGet you should append your parameters to the url manually

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

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

or use the post request the difference between get and post requests are explained here, if you are interested

或者使用 post 请求,这里解释get 和 post 请求之间的区别,如果你有兴趣的话

回答by 9re

To build uri with get parameters, Uri.Builder provides a more effective way.

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

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

回答by siamii

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

URI 文档

Note: url = new URI(...)is buggy

注意:url = new URI(...)有问题

回答by n1ckolas

As of HttpComponents4.2+there is a new class URIBuilder, which provides convenient way for generating URIs.

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

You can use either create URI directly from String URL:

您可以直接从字符串 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();

Otherwise, you can specify all parameters explicitly:

否则,您可以明确指定所有参数:

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

Once you have created URIobject, then you just simply need to create HttpGetobject and perform it:

一旦你创建了URI对象,那么你只需要创建HttpGet对象并执行它:

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

回答by Yorty Ruiz

    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");

回答by Beno Arakelyan

If you have constant URLI recommend use simplified http-requestbuilt on apache http.

如果您有常量,URL我建议使用基于 apache http 的简化http 请求

You can build your client as following:

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

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

Note: There are many useful methods to manipulate your response.

注意:有许多有用的方法可以操作您的响应。