Службы приложений Azure - невозможно вызвать API через клиент Android - PullRequest
0 голосов
/ 06 мая 2019

Я пытаюсь вызвать простой API через Android SDK.

Я создал службу приложения, и, поскольку у меня возникли некоторые трудности с подключением собственного приложения Android к бэкэнду службы, я попыталсясначала простой тест.

Я создал Easy API с именем test_api1 через портал со следующим кодом:

module.exports = {
    "get": function (req, res, next) {
        res.status(200).type('text').send("1");
    },
    "post": function (req, res, next) {
        res.status(200).type('text').send("2");
    }
};

API не требует аутентификации для этого(все определено anonymous).

Когда я просто вызываю его через браузер (перейдя к https://*.azurewebsites.net/api/test_api1), я могу видеть 1 в браузере, как и ожидалось.

Однако, когда я пытаюсь вызвать API через приложение, я получаю сообщение об ошибке.Вот код, который я использую для вызова API:

    private void testAPI() {
        Log.d(LOG_TAG, "Running API");
        ListenableFuture<JsonElement> res = this.azureClient.invokeApi("test_api1");
        Futures.addCallback(res, new FutureCallback<JsonElement>() {
            @Override
            public void onSuccess(@Nullable JsonElement result) {
                Log.d(LOG_TAG, "success");
                if (result != null) {
                    Log.d(LOG_TAG, result.toString());
                }
            }

            @Override
            public void onFailure(Throwable t) {
                Log.e(LOG_TAG, "failure", t);
            }
        });
    }

Где this.azureClient инициируется следующим образом через MainActivity:

    private void initAzureConnection(Context context) {
        try {
            azureClient = new MobileServiceClient(
                    "https://*.azurewebsites.net",
                    context
            );
        } catch (MalformedURLException ex) {
            Log.e(LOG_TAG, "failed to initialize azure client", ex);
        }
    }

Когда я запускаюПриложение я получаю следующую ошибку:

2019-05-06 19:14:15.959 5414-5414/com.*.* E/MAIN_ACTIVITY: failure
    com.microsoft.windowsazure.mobileservices.MobileServiceException: Error while processing request.
        at com.microsoft.windowsazure.mobileservices.http.MobileServiceConnection$1.onNext(MobileServiceConnection.java:139)
        at com.microsoft.windowsazure.mobileservices.MobileServiceClient$15.handleRequest(MobileServiceClient.java:1611)
        at com.microsoft.windowsazure.mobileservices.http.MobileServiceConnection.start(MobileServiceConnection.java:114)
        at com.microsoft.windowsazure.mobileservices.http.RequestAsyncTask.doInBackground(RequestAsyncTask.java:78)
        at com.microsoft.windowsazure.mobileservices.http.RequestAsyncTask.doInBackground(RequestAsyncTask.java:35)
        at android.os.AsyncTask$2.call(AsyncTask.java:333)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
     Caused by: java.net.SocketTimeoutException: timeout
        at okio.Okio$4.newTimeoutException(Okio.java:232)
        at okio.AsyncTimeout.exit(AsyncTimeout.java:285)
        at okio.AsyncTimeout$2.read(AsyncTimeout.java:241)
        at okio.RealBufferedSource.indexOf(RealBufferedSource.java:354)
        at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:226)
        at okhttp3.internal.http1.Http1Codec.readHeaderLine(Http1Codec.java:215)
        at okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:189)
        at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:88)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254)
        at okhttp3.RealCall.execute(RealCall.java:92)
        at com.microsoft.windowsazure.mobileservices.http.ServiceFilterRequestImpl.execute(ServiceFilterRequestImpl.java:164)
        at com.microsoft.windowsazure.mobileservices.http.MobileServiceConnection$1.onNext(MobileServiceConnection.java:122)
        at com.microsoft.windowsazure.mobileservices.MobileServiceClient$15.handleRequest(MobileServiceClient.java:1611) 
        at com.microsoft.windowsazure.mobileservices.http.MobileServiceConnection.start(MobileServiceConnection.java:114) 
        at com.microsoft.windowsazure.mobileservices.http.RequestAsyncTask.doInBackground(RequestAsyncTask.java:78) 
        at com.microsoft.windowsazure.mobileservices.http.RequestAsyncTask.doInBackground(RequestAsyncTask.java:35) 
        at android.os.AsyncTask$2.call(AsyncTask.java:333) 
        at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
        at java.lang.Thread.run(Thread.java:764) 
     Caused by: java.net.SocketException: socket is closed
        at com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream.read(ConscryptFileDescriptorSocket.java:551)
        at okio.Okio$2.read(Okio.java:140)
        at okio.AsyncTimeout$2.read(AsyncTimeout.java:237)
        at okio.RealBufferedSource.indexOf(RealBufferedSource.java:354) 
        at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:226) 
        at okhttp3.internal.http1.Http1Codec.readHeaderLine(Http1Codec.java:215) 
        at okhttp3.internal.http1.Http1Codec.readResponseHeaders(Http1Codec.java:189) 
        at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:88) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) 
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) 
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) 
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254) 
        at okhttp3.RealCall.execute(RealCall.java:92) 
        at com.microsoft.windowsazure.mobileservices.http.ServiceFilterRequestImpl.execute(ServiceFilterRequestImpl.java:164) 
        at com.microsoft.windowsazure.mobileservices.http.MobileServiceConnection$1.onNext(MobileServiceConnection.java:122) 
        at com.microsoft.windowsazure.mobileservices.MobileServiceClient$15.handleRequest(MobileServiceClient.java:1611) 
        at com.microsoft.windowsazure.mobileservices.http.MobileServiceConnection.start(MobileServiceConnection.java:114) 
        at com.microsoft.windowsazure.mobileservices.http.RequestAsyncTask.doInBackground(RequestAsyncTask.java:78) 
        at com.microsoft.windowsazure.mobileservices.http.RequestAsyncTask.doInBackground(RequestAsyncTask.java:35) 
        at android.os.AsyncTask$2.call(AsyncTask.java:333) 
        at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
        at java.lang.Thread.run(Thread.java:764) 

Спасибо!

1 Ответ

0 голосов
/ 10 мая 2019

Это похоже на проблему с сетью, и эта ошибка не может быть решена клиентом, так как это проблема, связанная с сетью. Однако вы можете повторить попытку подключения несколько раз. Это может работать как обходной путь, пока реальная проблема не будет устранена.

Пример кода:

for (int retries = 0; retries < 3; retries++) {
    try {
        final HttpClient client = createHttpClientWithDefaultSocketFactory(null, null);
        final HttpResponse response = client.execute(get);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new IllegalStateException("GET Request on '" + get.getURI().toString() + "' resulted in " + statusCode);
        } else {                
            return response.getEntity();
        }
    } catch (final java.net.SocketTimeoutException e) {
        // connection timed out...let's try again                
    }
}

Один из способов эффективной обработки - определить тайм-аут соединения, а затем обработать его с помощью блока try catch. Надеюсь, в будущем это поможет любому, кто столкнется с той же проблемой.

HttpUrlConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(7000); //set the timeout in milliseconds

Надеюсь, это поможет.

...