Volley - NoConnectionError,ProtocolException&超出内容长度限制

时间:2016-04-18 16:41:02

标签: android android-volley android-image android-networking

我正在尝试使用Volley将图像上传到我的服务器,但我一直收到错误:

com.android.volley.NoConnectionError: java.net.ProtocolException: exceeded content-length limit of n bytes

其中n是imageData的长度。

存在连接,因此NoConnectionError部分内容很奇怪。

以下是所有相关代码:

public class UploadPhotoRequest extends BaseRequest<Boolean> {

public static final String CONTENT_TYPE = "Content-Type";
public static final String CONTENT_LENGTH = "Content-Length";
public static final String PREFIX = "--";
private String imageData;
private String fileName;

private static final String BOUNDARY = "#BOUNDARY#";

public UploadPhotoRequest(String authToken, String clientKey, int method, String url,
                          String imageData, String fileName) {
    super(authToken, clientKey, method, url);
    this.imageData = imageData;
    this.fileName = fileName;
}

@Override
public byte[] getBody() {
    try {
        String appendMe = buildBodyString(PREFIX, BOUNDARY, fileName, imageData);
        return appendMe.getBytes(PROTOCOL_CHARSET);
    } catch (UnsupportedEncodingException e) {
        Logger.e("UploadPhotoRequest", "Failed trying to get bytes for upload");
        return null;
    }
}

@Override
public String getBodyContentType() {
    return "multipart/form-data;boundary=" + BOUNDARY;
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    HashMap<String, String> headers = new HashMap<>();
    headers.put(CONTENT_TYPE, getBodyContentType());
    //Other server headers
    headers.put(CONTENT_LENGTH, String.valueOf(imageData.length()));
    return headers;
}

@Override
public Response<Boolean> parseNetworkResponse(NetworkResponse response) {
    if (isReqSuccessful(response)) {
        return Response.success(true, HttpHeaderParser.parseCacheHeaders(response));
    } else {
        return Response.error(new VolleyError(ErrorMessages.UPLOAD_PHOTO));
    }
}

private String buildBodyString(String prefix, String boundary, String fileName, String image) {
    StringBuffer stringBuilder = new StringBuffer();
    stringBuilder
            .append(prefix)
            .append(boundary)
            .append("Content-Disposition: form-data; name=\"user[image]\"; filename=\"")
            .append(fileName)
            .append("\"")
            .append("Content-Type: image/jpeg")
            .append(image)
            .append(prefix)
            .append(boundary)
            .append(prefix);
    return stringBuilder.toString();
}

}

BaseRequest从Request扩展并包含一些常见信息&amp;我的其他要求使用的助手。

有问题的图像编码如下:

 String encodedImage = Base64.encodeToString(outputStream.toByteArray(),
                            Base64.DEFAULT);

有没有人经历过这个?

0 个答案:

没有答案