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

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

我知道我错过了一些东西,任何帮助都是非常感激的。

237978 次浏览

The method

setParams()

喜欢

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

只添加 HttpProtocol 参数。

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

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

或使用邮寄申请 如果您感兴趣,我们将解释获取请求和发布请求之间的区别 给你

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

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

我使用 NameValuePair 和 URLEncodedUtils 的 List 来创建我想要的 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;
}
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(...)有问题

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

您可以直接使用 String 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();

Once you have created URI object, then you just simply need to create HttpGet object and perform it:

//create GET request
HttpGet httpGet = new HttpGet(uri);
//perform request
httpClient.execute(httpGet ...//additional parameters, handle response etc.
    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");

如果你有不变的 URL,我建议使用简化的 http-request建立在阿帕奇 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());
}

注意: 有许多有用的方法来操纵您的响应。