如何设置Volley响应的超时时间?

时间:2018-12-03 09:06:09

标签: android flask android-volley

我正在尝试在我的android应用中向带有Volley和MultipartEntity的外部flask应用发出发布请求,但是flask应用花费的时间太长而无法响应,并且正在调用Response.ErrorListener。我想延长响应的超时时间,以便烧瓶端有它需要响应的时间。

这是我的MultipartEntity代码:

    public MultipartRequest(String url, Response.ErrorListener errorListener, 
    Response.Listener<String> listener, File file, String stringPart)
    {
        super(Method.POST, url, errorListener);

        mListener = listener;
        mFilePart = file;
        mStringPart = stringPart;
        buildMultipartEntity();
    }

    private void buildMultipartEntity()
    {
        entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
    }

    @Override
    public String getBodyContentType()
    {
        return entity.getContentType().getValue();
    }

    @Override
    public byte[] getBody() throws AuthFailureError
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try
        {
            entity.writeTo(bos);
        }
        catch (IOException e)
        {
            VolleyLog.e("IOException writing to ByteArrayOutputStream");
        }
        return bos.toByteArray();
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response)
    {
        return Response.success("Uploaded", getCacheEntry());
    }

    @Override
    protected void deliverResponse(String response)
    {
        mListener.onResponse(response);
    }
}

这是我使用该代码发送图像的功能:

public void sendImg(View v){
    File pic = (File) getIntent().getExtras().get("pic");
    String str = "img";
    MultipartRequest multipartRequest = new 
MultipartRequest("http://100.64.113.81/digitize",
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("img", "That didn't work!");
                }
            },
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("server", response);
                }
            }, pic, str);
    RequestQueue queue = Volley.newRequestQueue(this);
    queue.add(multipartRequest);
}

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

尝试这个

stringRequest.setRetryPolicy(new RetryPolicy() {
            @Override
            public int getCurrentTimeout() {
                return 10000;
            }

            @Override
            public int getCurrentRetryCount() {
                return 10000;
            }

            @Override
            public void retry(VolleyError error) throws VolleyError {

            }
        });
        MyApplication.getInstance().addToRequestQueue(stringRequest);