Programing

발리 타임 아웃 시간 변경

crosscheck 2020. 5. 17. 15:46
반응형

발리 타임 아웃 시간 변경


Android에 새로운 Volley 프레임 워크를 사용하여 서버에 요청합니다. 그러나 응답하지만 응답을 받기 전에 시간이 초과됩니다.

이 코드를 추가하려고했습니다.

HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);

에서 HttpClientStack다른 정수 (50000)에 발리 프레임 워크,하지만 여전히 시간이 초과 50초 전에.

시간 초과를 긴 값으로 변경하는 방법이 있습니까?


참조 Request.setRetryPolicy()및 생성자에 대한 DefaultRetryPolicy

JsonObjectRequest myRequest = new JsonObjectRequest(Method.GET,
        url, null,
        new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG, "Error: " + error.getMessage());
            }
});

myRequest.setRetryPolicy(new DefaultRetryPolicy(
        MY_SOCKET_TIMEOUT_MS, 
        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

안드로이드 발리 타임 아웃을 처리하려면 RetryPolicy

재시도 정책

  • 발리는 요청에 대해 RetryPolicy를 쉽게 구현할 수있는 방법을 제공합니다.
  • 발리는 모든 요청에 ​​대해 기본 Socket & ConnectionTImeout을 5 초로 설정합니다.

RetryPolicy 시간 초과가 발생했을 때 특정 요청을 다시 시도하는 방법에 대한 논리를 구현해야하는 인터페이스입니다.

이 세 가지 매개 변수를 처리합니다

  • 제한 시간-재 시도 할 때마다 소켓 제한 시간을 밀리 초로 지정합니다.
  • 재시도 횟수-재시도 횟수입니다.
  • 백 오프 멀티 플라이어-모든 재 시도에 대해 소켓에 설정된 지수 시간을 결정하는 데 사용되는 멀티 플라이어입니다.

예를 들어. 이 값으로 RetryPolicy를 생성 한 경우

시간 초과-3000ms, 재시도 횟수-2, 백 오프 승수-2.0

재시도 1

  • 시간 = 시간 + (시간 * 백 오프 승수);
  • 시간 = 3000 + 6000 = 9000ms
  • 소켓 타임 아웃 = 시간;
  • 소켓 시간 초과가 9 초인 요청

재시도 2 :

  • 시간 = 시간 + (시간 * 백 오프 승수);
  • 시간 = 9000 + 18000 = 27000ms
  • 소켓 타임 아웃 = 시간;
  • 27 초의 소켓 제한 시간 초과로 요청이 전달됨

따라서 재시도 2 가 끝날 때 소켓 시간 초과가 발생하면 Volley는 TimeoutErrorUI 오류 응답 핸들러에를 던질 것 입니다.

//Set a retry policy in case of SocketTimeout & ConnectionTimeout Exceptions. 
//Volley does retry for you if you have specified the policy.
jsonObjRequest.setRetryPolicy(new DefaultRetryPolicy(5000, 
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

Just to contribute with my approach. As already answered, RetryPolicy is the way to go. But if you need a policy different the than default for all your requests, you can set it in a base Request class, so you don't need to set the policy for all the instances of your requests.

Something like this:

public class BaseRequest<T> extends Request<T> {

    public BaseRequest(int method, String url, Response.ErrorListener listener) {
        super(method, url, listener);
        setRetryPolicy(getMyOwnDefaultRetryPolicy());
    }
}

In my case I have a GsonRequest which extends from this BaseRequest, so I don't run the risk of forgetting to set the policy for an specific request and you can still override it if some specific request requires to.


/**
 * @param request
 * @param <T>
 */
public <T> void addToRequestQueue(Request<T> request) {

    request.setRetryPolicy(new DefaultRetryPolicy(
            MY_SOCKET_TIMEOUT_MS,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    getRequestQueue().add(request);
}

req.setRetryPolicy(new DefaultRetryPolicy(
    MY_SOCKET_TIMEOUT_MS, 
    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

You can set MY_SOCKET_TIMEOUT_MS as 100. Whatever you want to set this to is in milliseconds. DEFAULT_MAX_RETRIES can be 0 default is 1.


int MY_SOCKET_TIMEOUT_MS=500;

 stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                MY_SOCKET_TIMEOUT_MS,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

Another way of doing it is in custom JsonObjectRequest by:

@Override
public RetryPolicy getRetryPolicy() {
    // here you can write a custom retry policy and return it
    return super.getRetryPolicy();
}

Source: Android Volley Example


Alternative solution if all above solutions are not working for you

By default, Volley set timeout equally for both setConnectionTimeout() and setReadTimeout() with the value from RetryPolicy. In my case, Volley throws timeout exception for large data chunk see:

com.android.volley.toolbox.HurlStack.openConnection(). 

My solution is create a class which extends HttpStack with my own setReadTimeout() policy. Then use it when creates RequestQueue as follow:

Volley.newRequestQueue(mContext.getApplicationContext(), new MyHurlStack())

I ended up adding a method setCurrentTimeout(int timeout) to the RetryPolicy and it's implementation in DefaultRetryPolicy.

Then I added a setCurrentTimeout(int timeout) in the Request class and called it .

This seems to do the job.

Sorry for my laziness by the way and hooray for open source.

참고URL : https://stackoverflow.com/questions/17094718/change-volley-timeout-duration

반응형