Не удается подключиться к API погоды - PullRequest
1 голос
/ 30 апреля 2020

Мне нужна помощь. Вот мои коды и мои ошибки. Я новичок и использую weather.org для API. Я искал по всему inte rnet, но все они имеют одинаковый ответ. Это

android: usedCleartextTraffic = "true" и android: networkSecurityConfig = "@ xml / network_security_config"

Мой XML тег приложения имеет:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

<application
    ...
    android:usesCleartextTraffic="true"
    android:networkSecurityConfig="@xml/network_security_config"
    ...>

    <uses-library android:name="org.apache.http.legacy"
        android:required="false"/>

</application>

А моя основная активность:

    public void getData(){
    final String url = "http://api.openweathermap.org/data/2.5/weather?q=Manila&appid=1fef2628db7b44791ee1029f1999137a&units=imperial";

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

        @SuppressLint("SetTextI18n")
        @Override
        public void onResponse(JSONObject response) {


            try {
                JSONObject main_object = response.getJSONObject("main");
                JSONArray array = response.getJSONArray("weather");
                String temp = String.valueOf(main_object.getDouble("temp"));
                String city = response.getString("name");
                JSONObject country_object = response.getJSONObject("sys");
                String country = country_object.getString("country");


                Toast.makeText(MainActivity.this, "Try. Catch3", Toast.LENGTH_LONG).show();

                txtTemp.setText(temp + "°C");
                txtMyLocation.setText(city + "\n" + country);

            } catch (JSONException e) {

                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
            //I made this toast to make sure that the error goes here and I was right. The toast shows up.
            error.printStackTrace();
        }
    }
    );
    queue = Volley.newRequestQueue(this);
    queue.add(req);
}

Мой build.gradle имеет:

implementation 'com.android.volley:volley:1.1.0'

Мой netword_security_config. xml это:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">http://api.openweathermap.org</domain>
    </domain-config>
</network-security-config>

Тогда вот моя ошибка:

2020-04-30 07:46:08.094 24706-24706/com.example.demo W/BugManager: ##### register,mFd=49
2020-04-30 07:46:08.111 24706-24706/com.example.demo W/System.err: com.android.volley.NoConnectionError: java.io.IOException: Cleartext HTTP traffic to api.openweathermap.org not permitted
2020-04-30 07:46:08.111 24706-24706/com.example.demo W/System.err:     at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:177)
2020-04-30 07:46:08.111 24706-24706/com.example.demo W/System.err:     at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:120)
2020-04-30 07:46:08.111 24706-24706/com.example.demo W/System.err:     at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:87)
2020-04-30 07:46:08.111 24706-24706/com.example.demo W/System.err: Caused by: java.io.IOException: Cleartext HTTP traffic to api.openweathermap.org not permitted
2020-04-30 07:46:08.111 24706-24706/com.example.demo W/System.err:     at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:115)
2020-04-30 07:46:08.111 24706-24706/com.example.demo W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:458)
2020-04-30 07:46:08.111 24706-24706/com.example.demo W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
2020-04-30 07:46:08.111 24706-24706/com.example.demo W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:538)
2020-04-30 07:46:08.111 24706-24706/com.example.demo W/System.err:     at com.android.volley.toolbox.HurlStack.executeRequest(HurlStack.java:99)
2020-04-30 07:46:08.111 24706-24706/com.example.demo W/System.err:     at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:131)
2020-04-30 07:46:08.111 24706-24706/com.example.demo W/System.err:  ... 2 more

Когда я редактирую http для https в MainActivity. java и network_security_config. xml, я получаю эту ошибку:

    2020-04-30 08:06:27.309 24975-24975/? I/om.example.dem: Late-enabling -Xcheck:jni
    2020-04-30 08:06:27.404 24975-24975/com.example.demo I/om.example.dem: The ClassLoaderContext is a special shared library.
    2020-04-30 08:06:27.486 24975-24975/com.example.demo I/Perf: Connecting to perf service.
    2020-04-30 08:06:27.542 24975-24975/com.example.demo W/om.example.dem: Accessing hidden method Landroid/graphics/drawable/Drawable;->getOpticalInsets()Landroid/graphics/Insets; (light greylist, linking)
    2020-04-30 08:06:27.542 24975-24975/com.example.demo W/om.example.dem: Accessing hidden field Landroid/graphics/Insets;->left:I (light greylist, linking)
    2020-04-30 08:06:27.542 24975-24975/com.example.demo W/om.example.dem: Accessing hidden field Landroid/graphics/Insets;->right:I (light greylist, linking)
    2020-04-30 08:06:27.542 24975-24975/com.example.demo W/om.example.dem: Accessing hidden field Landroid/graphics/Insets;->top:I (light greylist, linking)
    2020-04-30 08:06:27.542 24975-24975/com.example.demo W/om.example.dem: Accessing hidden field Landroid/graphics/Insets;->bottom:I (light greylist, linking)
    2020-04-30 08:06:27.587 24975-24975/com.example.demo W/om.example.dem: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
    2020-04-30 08:06:27.587 24975-24975/com.example.demo W/om.example.dem: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
    2020-04-30 08:06:27.621 24975-24975/com.example.demo W/om.example.dem: Accessing hidden method Landroid/widget/TextView;->getTextDirectionHeuristic()Landroid/text/TextDirectionHeuristic; (light greylist, linking)
    2020-04-30 08:06:27.625 24975-24975/com.example.demo W/om.example.dem: Accessing hidden method Landroid/graphics/FontFamily;-><init>()V (light greylist, reflection)
    2020-04-30 08:06:27.625 24975-24975/com.example.demo W/om.example.dem: Accessing hidden method Landroid/graphics/FontFamily;->addFontFromAssetManager(Landroid/content/res/AssetManager;Ljava/lang/String;IZIII[Landroid/graphics/fonts/FontVariationAxis;)Z (light greylist, reflection)
    2020-04-30 08:06:27.625 24975-24975/com.example.demo W/om.example.dem: Accessing hidden method Landroid/graphics/FontFamily;->addFontFromBuffer(Ljava/nio/ByteBuffer;I[Landroid/graphics/fonts/FontVariationAxis;II)Z (light greylist, reflection)
    2020-04-30 08:06:27.625 24975-24975/com.example.demo W/om.example.dem: Accessing hidden method Landroid/graphics/FontFamily;->freeze()Z (light greylist, reflection)
    2020-04-30 08:06:27.625 24975-24975/com.example.demo W/om.example.dem: Accessing hidden method Landroid/graphics/FontFamily;->abortCreation()V (light greylist, reflection)
    2020-04-30 08:06:27.625 24975-24975/com.example.demo W/om.example.dem: Accessing hidden method Landroid/graphics/Typeface;->createFromFamiliesWithDefault([Landroid/graphics/FontFamily;Ljava/lang/String;II)Landroid/graphics/Typeface; (light greylist, reflection)
    2020-04-30 08:06:27.653 24975-25019/com.example.demo I/DpmTcmClient: RegisterTcmMonitor from: $Proxy0
    2020-04-30 08:06:27.656 24975-24975/com.example.demo D/OpenGLRenderer: Skia GL Pipeline
    2020-04-30 08:06:27.659 24975-25019/com.example.demo D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
    2020-04-30 08:06:27.659 24975-24975/com.example.demo W/BugManager: ##### register,mFd=48
    2020-04-30 08:06:27.676 24975-24975/com.example.demo W/System.err: com.android.volley.NoConnectionError: java.io.IOException: Cleartext HTTP traffic to api.openweathermap.org not permitted
    2020-04-30 08:06:27.676 24975-24975/com.example.demo W/System.err:     at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:177)
    2020-04-30 08:06:27.676 24975-24975/com.example.demo W/System.err:     at com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:120)
    2020-04-30 08:06:27.676 24975-24975/com.example.demo W/System.err:     at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:87)
    2020-04-30 08:06:27.676 24975-24975/com.example.demo W/System.err: Caused by: java.io.IOException: Cleartext HTTP traffic to api.openweathermap.org not permitted
    2020-04-30 08:06:27.676 24975-24975/com.example.demo W/System.err:     at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:115)
    2020-04-30 08:06:27.676 24975-24975/com.example.demo W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:458)
    2020-04-30 08:06:27.676 24975-24975/com.example.demo W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
    2020-04-30 08:06:27.677 24975-24975/com.example.demo W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:538)
    2020-04-30 08:06:27.677 24975-24975/com.example.demo W/System.err:     at com.android.volley.toolbox.HurlStack.executeRequest(HurlStack.java:99)
    2020-04-30 08:06:27.677 24975-24975/com.example.demo W/System.err:     at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:131)
    2020-04-30 08:06:27.677 24975-24975/com.example.demo W/System.err:  ... 2 more
    2020-04-30 08:06:27.699 24975-25024/com.example.demo I/Adreno: QUALCOMM build                   : eb3073a, I21de9e011e
    Build Date                       : 05/14/19
    OpenGL ES Shader Compiler Version: EV031.25.19.01
    Local Branch                     : 
    Remote Branch                    : refs/tags/AU_LINUX_ANDROID_LA.UM.7.1.R1.09.00.00.461.091
    Remote Branch                    : NONE
    Reconstruct Branch               : NOTHING
    2020-04-30 08:06:27.699 24975-25024/com.example.demo I/Adreno: Build Config                     : S P 6.0.9 AArch64
    2020-04-30 08:06:27.706 24975-25024/com.example.demo I/Adreno: PFP: 0x016ee180, ME: 0x00000000
    2020-04-30 08:06:27.709 24975-25024/com.example.demo I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 1
    2020-04-30 08:06:27.709 24975-25024/com.example.demo I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 1
    2020-04-30 08:06:27.710 24975-25024/com.example.demo I/OpenGLRenderer: Initialized EGL, version 1.4
    2020-04-30 08:06:27.710 24975-25024/com.example.demo D/OpenGLRenderer: Swap behavior 2
    2020-04-30 08:06:27.722 24975-24975/com.example.demo V/BugManager_JNI: bug message start: fd=48,tag =0X01004801
    2020-04-30 08:06:27.722 24975-24975/com.example.demo V/BugManager_JNI: bug message copy: fd=48,msgid =6703,len=72,msg={"activity":"com.example.demo/com.example.demo.MainActivity","frames":2}
    2020-04-30 08:06:27.722 24975-24975/com.example.demo V/BugManager_JNI: bug message stop: fd =48,msgid =6703
    2020-04-30 08:06:27.807 24975-24975/com.example.demo V/BugManager_JNI: bug message start: fd=48,tag =0X01004801
    2020-04-30 08:06:27.807 24975-24975/com.example.demo V/BugManager_JNI: bug message copy: fd=48,msgid =6705,len=72,msg={"activity":"com.example.demo/com.example.demo.MainActivity","frames":4}
    2020-04-30 08:06:27.807 24975-24975/com.example.demo V/BugManager_JNI: bug message stop: fd =48,msgid =6705
    2020-04-30 08:06:31.210 24975-24975/com.example.demo V/BugManager_JNI: bug message start: fd=48,tag =0X01004801
    2020-04-30 08:06:31.211 24975-24975/com.example.demo V/BugManager_JNI: bug message copy: fd=48,msgid =6706,len=72,msg={"activity":"com.example.demo/com.example.demo.MainActivity","frames":1}
    2020-04-30 08:06:31.211 24975-24975/com.example.demo V/BugManager_JNI: bug message stop: fd =48,msgid =6706

1 Ответ

0 голосов
/ 30 апреля 2020

Просто не может служить цели, но я использовал OkHttp вместо Volley, и это происходило. Снова я перестал работать Volley долгое время go.

Во всяком случае, простой пример,

OkHttpUtilAsyn c .class

private final static String URL = "http://api.openweathermap.org/data/2.5/weather?q=Manila&appid=1fef2628db7b44791ee1029f1999137a&units=imperial/posts/1"; //1 object
    private final static String TAG = OkHttpUtilAsync.class.getSimpleName();

private OkHttpClient okHttpClient;
private Request request;
private String result = "";
private ResponseBody responseBody;
private MediaType mediaType;


OkHttpUtilAsync() {
    setUpClientAndRequest();
}

void fetchNetwork() {
    Log.d(TAG, "fetchNetwork()");
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.i(TAG, "onFailure()");
            call.cancel();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.i(TAG, "onResponse()");
            processResponse(response);


        }
    });

}

private void setUpClientAndRequest() {
    Log.w(TAG, "setUpClientAndRequest()");

    okHttpClient = new OkHttpClient();
    request = new Request.Builder().url(URL).build();
}

private void processResponse(Response response) {
    Log.i(TAG, "processResponse()");

    if (response != null) {
        Log.w(TAG, "Response not Null");

        if (response.isSuccessful()) {
            Log.wtf(TAG, "Response is Successful : " + response.isSuccessful());

            //                     responseBody = response.body(); has the RESULT
            Log.v(TAG, " result = " + response.body());


        } else {
            Log.wtf(TAG, "Response is not Successful : " + response.isSuccessful());
        }
        //close the Response
        response.close();

    } else {
        Log.w(TAG, "Response ==== Null");
    }
}

и вызвать его из MainActivity

OkHttpUtilAsync okHttpUtilAsync=new OkHttpUtilAsync();
        okHttpUtilAsync.fetchNetwork();

Нет необходимости устанавливать какой-либо простой текст и удалять все эти настройки безопасности сети из xml. gradle implementation 'com.squareup.okhttp3:okhttp:3.10.0'

...