14

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

我只是不想用我的 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);

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

任何提示都非常感谢!

4

2 回答 2

2

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

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

于 2010-12-13T09:32:35.083 回答
1

试图让它以第一种方式工作,但似乎HttpParams界面并不是为此而构建的。在谷歌上搜索了一段时间后,我发现了这个 SO 答案来解释它:

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

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

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

为了设置连接和请求超时,我混合使用了HttpParamsList<NameValuePair>,它功能齐全并使用AndroidHttpClientAPI 8 中提供的类:

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-08-14T11:50:49.120 回答