Не удалось отправить запрос через OkHttp в android - PullRequest
1 голос
/ 08 марта 2020

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

W/System.err: java.net.UnknownServiceException: CLEARTEXT communication to 35.226.157.128 not permitted by network security policy
        at okhttp3.internal.connection.RealConnection.connect(RealConnection.kt:176)
        at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:233)
        at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.kt:107)
        at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.kt:75)
        at okhttp3.internal.connection.RealCall.initExchange$okhttp(RealCall.kt:245)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:32)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:82)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:74)
W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:197)
        at okhttp3.internal.connection.RealCall.execute(RealCall.kt:148)
        at com.example.plantai.CropImage$1.run(CropImage.java:228)
        at java.lang.Thread.run(Thread.java:764)

Код для отправки запроса следующий:

public void scanClick(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                isConnected();
                OkHttpClient client = new OkHttpClient().newBuilder()
                        .build();
                Log.d("req" , "Resquesting ...");
                //MediaType mediaType = MediaType.parse("text/plain");

                RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                        .addFormDataPart("photo",Environment.getExternalStorageDirectory()
                                        +"/Android/PlantAi/crop.jpg",
                                RequestBody.create(MediaType.parse("application/octet-stream"),
                                        new File(Environment.getExternalStorageDirectory()
                                                +"/Android/PlantAi/crop.jpg")))
                        .build();
                Log.d("req" , "Body created");


                Request request = new Request.Builder()
                        .url("http://35.226.157.128:80/PlantAi/upload-manager.php")
                        .method("POST", body)
                        .addHeader("Content-Transfer-Encoding", "multipart/form-data")
                        .build();
                Log.d("req" , "Request Build.");


                try {
                    Log.d("req" , "Sending request");

                    Response response = client.newCall(request).execute();
                    System.out.println("Response ====>  " + response);

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        }).start();

    }

Согласно Android 8: HTTP-трафик в незашифрованном виде c не разрешено I Добавлено

res / xml / network_security_config. xml

android: usedCleartextTraffic = "true"

в AndroidManifest, но он не работает. Использование «https: //» вместо «http: //» не будет работать для моего сервера, это выдает ошибку вроде

W / System.err: javax. net .ssl.SSLHandshakeException : Рукопожатие не удалось

Что я здесь не так делаю?

1 Ответ

0 голосов
/ 08 марта 2020

Вы забыли что-то добавить в network_security_config. xml.

res / xml / network_security_config. xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config xmlns:android="http://schemas.android.com/apk/res/android">
    <base-config cleartextTrafficPermitted="false" />
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">35.226.157.128</domain>
    </domain-config>
</network-security-config>

AndroidManifest. xml

<application
  android:allowBackup="true"
  android:icon="@mipmap/ic_launcher"
  android:label="@string/app_name"
  android:roundIcon="@mipmap/ic_launcher_round"
  android:supportsRtl="true"
  android:theme="@style/AppTheme"
  android:networkSecurityConfig="@xml/network_security_config">

  ...

</application>
...