如何在android中为HttpGet请求添加NameValuePairs

问题描述 投票:2回答:4

在行:httpget.setEntity(new UrlEncodedFormEntity(nameValuePairs));

我收到的错误是:The method setEntity(UrlEncodedFormEntity) is undefined for the type HttpGet


码:

        HttpClient httpclient = new DefaultHttpClient();
        // Add the header data for the request
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("phonenumber","12345"));
        nameValuePairs.add(new BasicNameValuePair("authtoken", "12345"));
        HttpGet httpget = new HttpGet(url);
        httpget.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httpget);
android http-get
4个回答
6
投票

GET请求没有可以包含实体的主体,您要包含的参数应该内置到URL本身中。

一个干净的方法是使用URIBuilder

URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost(host).setPort(port).setPath(yourpath)
.setParameter("parts", "all")
.setParameter("action", "finish");

3
投票

尝试使用BasicNameValuePair List添加params并从URLEncodedUtils获取格式化的字符串,该字符串连接到url:

HttpClient httpclient = new DefaultHttpClient();
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("phonenumber", "12345"));
params.add(new BasicNameValuePair("authtoken", "12345"));
HttpGet httpget = new HttpGet(url+"?"+URLEncodedUtils.format(params, "utf-8"));
HttpResponse response = httpclient.execute(httpget);

0
投票

试试这种方式,

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

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

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

    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
投票

原因是因为setEntity方法属于HttpPost。不是HttpGet你只需将HttpGet更改为HttpPost即可纠正错误。

HttpPost httppost = new HttpPost(url);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

也在你的PHP代码中将所有$_GET["your key"];方法更改为$_POST["your key"];

© www.soinside.com 2019 - 2024. All rights reserved.