【问题标题】:Can't get HttpParams working with Postrequest无法让 HttpParams 与 Postrequest 一起使用
【发布时间】:2011-05-24 09:22:55
【问题描述】:

我无法从 Android-API 中获取 HttpParams-stuff。

我只是不想在我的 Postrequest 中发送一些简单的参数。一切正常,除了参数。为postrequest设置参数的代码:

HttpParams params = new BasicHttpParams();
params.setParameter("password", "secret");
params.setParameter("name", "testuser");
postRequest.setParams(params);

似乎这段代码根本没有添加任何参数,因为服务器总是回答我的请求缺少“名称”参数。

实际按预期工作的示例:

ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("name", "testuser"));
postParameters.add(new BasicNameValuePair("password", "secret"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
postRequest.setEntity(formEntity);

但我想使用第一个示例的版本,因为它更易于阅读和理解。

任何提示都非常感谢!

【问题讨论】:

  • +1 -- 同样的问题...切换到使用 ArrayList 并且现在一切正常...不明白为什么与 HttpParams 相同的逻辑不起作用!跨度>

标签: android http android-internet


【解决方案1】:

一旦我遇到了同样的问题,我就用和你一样的方式解决了它……我记得我发现了一些关于为什么这不起作用的话题。这与 Apache 在服务器端的库实现有关。

很遗憾,我现在找不到那个话题,但如果我是你,我会让它继续工作,不会太担心代码的“优雅”,因为你可能无能为力,如果可以的话,这根本不实用。

【讨论】:

  • 是的,你说得对,但我不明白。如果 HttpParams 显然根本不起作用,为什么还有 API?
【解决方案2】:

尝试以第一种方式使其工作,但似乎HttpParams 接口不是为此而构建的。谷歌了一会儿,我发现this SO answer 解释它:

HttpParams 接口不是用于指定查询字符串参数,而是用于指定 HttpClient 对象的运行时行为。

不过,文档并不是那么具体:

HttpParams 接口表示定义组件运行时行为的不可变值的集合。

为了设置连接和请求超时,我混合使用了 HttpParamsList&lt;NameValuePair&gt;,它们功能齐全,并使用 API 8 中提供的 AndroidHttpClient 类:

public HttpResponse securityCheck(String loginUrl, String name, String password) {
    AndroidHttpClient client = AndroidHttpClient.newInstance(null);
    HttpPost requestLogin = new HttpPost(
            loginUrl + "?");

    //Set my own params using NamaValuePairs
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("j_username", name));
    params.add(new BasicNameValuePair("j_password", password));

    //Set the timeouts using the wrapped HttpParams
    HttpParams httpParameters = client.getParams();
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    try {
        requestLogin
                .setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        HttpResponse response = client.execute(requestLogin);
        return response;
    } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
        return null;
    }finally {
        client.close();
    }
}

另请参阅:

【讨论】:

    猜你喜欢
    • 2014-10-31
    • 2018-01-02
    • 2016-11-14
    • 2015-02-01
    • 2019-05-10
    • 2017-11-20
    • 2019-05-17
    • 2018-06-02
    • 2019-04-30
    相关资源
    最近更新 更多