【问题标题】:Android-Async-Http Library post error?Android-Async-Http 库发布错误?
【发布时间】:2013-10-04 10:01:11
【问题描述】:

我目前正在使用android-async-http 库来发送发布/获取请求。我以前没有任何问题,但现在我意识到,如果我在没有图像数据的情况下发送此请求,它会给我超时错误。 (如果我也通过放置图像数据发送完全相同的请求,则没有错误。)

RequestParams params = new RequestParams();
params.add("mail", mail.getText().toString());
params.add("password", pass.getText().toString());

try {
if (!TextUtils.isEmpty(imagePath))
    params.put("image", new File(imagePath));
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(60000);
client.post("some_url", params, myResponseHandler);

这是什么原因? 提前致谢。

【问题讨论】:

  • 会不会只是你的服务器没有响应?
  • 但是在这篇文章之后,我放了一张图片,突然服务器开始响应?不,别这么想……应该还有别的。
  • 可能是你的服务器崩溃了,因为图片字段是空的
  • 不,不是因为这个。在下面查看我的答案,我已经发现了错误并解决了它。

标签: android asynchronous socket-timeout-exception android-async-http


【解决方案1】:

比较请求和响应后,我发现该案例是内容类型的。有了图片,它就发布了多部分,没有它,它就是别的东西。

所以我进入了库中的 RequestParams 类,并进行了这些更改。 现在它可以正常工作了。对于进一步的麻烦,我发布了我所做的更改。

我设置了一个标志来确定此请求是否应该作为多部分发布:

private boolean shouldUseMultiPart = false;

我创建了一个构造函数来设置这个参数:

public RequestParams(boolean shouldUseMultiPart) {
    this.shouldUseMultiPart = shouldUseMultiPart;
    init();
}

然后在 getEntity() 方法上我应用了这些行:

/**
 * Returns an HttpEntity containing all request parameters
 */
public HttpEntity getEntity() {
    HttpEntity entity = null;

    if (!fileParams.isEmpty()) {
        ...
    } else {
        if (shouldUseMultiPart) {
            SimpleMultipartEntity multipartEntity = new SimpleMultipartEntity();

            // Add string params
            for (ConcurrentHashMap.Entry<String, String> entry : urlParams
                    .entrySet()) {
                multipartEntity.addPart(entry.getKey(), entry.getValue());
            }

            // Add dupe params
            for (ConcurrentHashMap.Entry<String, ArrayList<String>> entry : urlParamsWithArray
                    .entrySet()) {
                ArrayList<String> values = entry.getValue();
                for (String value : values) {
                    multipartEntity.addPart(entry.getKey(), value);
                }
            }

            entity = multipartEntity;
        } else {
            try {
                entity = new UrlEncodedFormEntity(getParamsList(), ENCODING);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    return entity;
}

【讨论】:

  • 你如何在服务器端处理你的文件?我正在尝试实现相同的功能,但我无法在服务器 (asp.net) 上捕获我的图像文件 - 我看到除了文件之外的所有请求参数...
猜你喜欢
  • 2016-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多