从URL中获取JSON数据响应,使用Android如何实现?

huangapple 未分类评论49阅读模式
英文:

Get JSON Data response from URL using Android?

问题

以下是您提供的代码的翻译部分:

我正在尝试从URL获取JSON响应我已经多次尝试了下面的代码但是我无法获得响应请帮我解决这个问题

我正在使用API级别29

在这里我正在使用此URL获取数据URL -> https://api.androidhive.info/contacts/

我的代码

public class MainActivity extends AppCompatActivity {
    
    private final static String URL = "https://api.androidhive.info/contacts/";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        RequestQueue queue = Volley.newRequestQueue(this);
    
        JsonArrayRequest arrayRequest = new JsonArrayRequest(
            Request.Method.GET, URL, null, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d("Response : ", response.toString());
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d("Error : ", error.getMessage());
                }
            });
        queue.add(arrayRequest);
    }
}

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.volleyparsing">

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

    <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">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Logcat响应:

2020-05-03 22:19:49.600 11515-11515/? I/e.volleyparsin: Not late-enabling -Xcheck:jni (already on)
2020-05-03 22:19:49.749 11515-11515/? E/e.volleyparsin: Unknown bits set in runtime_flags: 0x8000
2020-05-03 22:19:53.066 11515-11515/com.example.volleyparsing D/Volley: [2] 2.onErrorResponse: Error :
2020-05-03 22:19:50.513 11515-11545/com.example.volleyparsing W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied)

请注意,这是您提供的内容的翻译版本,我已经按您的要求将代码部分翻译成了中文。

英文:

I am trying to get JSON response from a URL. I have tried below code several time but i couldn't get the response. Please Help me to sort this out

I am using API level 29

Here i am using this url for getting data, url -> https://api.androidhive.info/contacts/

My Code :

public class MainActivity extends AppCompatActivity {

    private final static String URL = &quot;https://api.androidhive.info/contacts/&quot;;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RequestQueue queue = Volley.newRequestQueue(this);

        JsonArrayRequest arrayRequest = new JsonArrayRequest(
                Request.Method.GET, URL,null,new Response.Listener&lt;JSONArray&gt;() {
            @Override
            public void onResponse(JSONArray response) {
                Log.d(&quot;Response : &quot;, response.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(&quot;Error : &quot;, error.getMessage());
            }
        });
        queue.add(arrayRequest);
    }
}

AndroidManifest.xml :

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    package=&quot;com.example.volleyparsing&quot;&gt;

    &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;

    &lt;application
        android:allowBackup=&quot;true&quot;
        android:icon=&quot;@mipmap/ic_launcher&quot;
        android:label=&quot;@string/app_name&quot;
        android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
        android:supportsRtl=&quot;true&quot;
        android:theme=&quot;@style/AppTheme&quot;&gt;
        &lt;activity android:name=&quot;.MainActivity&quot;&gt;
            &lt;intent-filter&gt;
                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;

                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
            &lt;/intent-filter&gt;
        &lt;/activity&gt;
    &lt;/application&gt;

&lt;/manifest&gt;

The Logcat response :

2020-05-03 22:19:49.600 11515-11515/? I/e.volleyparsin: Not late-enabling -Xcheck:jni (already on)
2020-05-03 22:19:49.749 11515-11515/? E/e.volleyparsin: Unknown bits set in runtime_flags: 0x8000
2020-05-03 22:19:53.066 11515-11515/com.example.volleyparsing D/Volley: [2] 2.onErrorResponse: Error :
2020-05-03 22:19:50.513 11515-11545/com.example.volleyparsing W/libc: Unable to set property &quot;qemu.gles&quot; to &quot;1&quot;: connection failed; errno=13 (Permission denied)

答案1

得分: 0

你的回应是 jsonObject 而不是 jsonArray。这就是你遇到解析错误的原因。请使用 jsonObject:

RequestQueue queue = Volley.newRequestQueue(context);

JsonObjectRequest objectRequest = new JsonObjectRequest(
        Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        JSONArray jsonArray = null;
        try {
            jsonArray = response.getJSONArray("contacts");
            Log.d("Response : ", jsonArray.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.d("Error : ", error.getMessage());
    }
});

queue.add(objectRequest);
英文:

Your response is jsonObject not jsonArray. That's way you are getting parsing error. Use jsonObject:

RequestQueue queue = Volley.newRequestQueue(context);

    JsonObjectRequest objectRequest = new JsonObjectRequest(
            Request.Method.GET, URL, null, new Response.Listener&lt;JSONObject&gt;() {
        @Override
        public void onResponse(JSONObject response) {
            JSONArray jsonArray = null;
            try {
                jsonArray = response.getJSONArray(&quot;contacts&quot;);
                Log.d(&quot;Response : &quot;, jsonArray.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(&quot;Error : &quot;, error.getMessage());
        }
    });

    queue.add(objectRequest);   

答案2

得分: 0

在您的清单文件的应用程序部分使用 android:usesCleartextTraffic="true"。

  <application
    ...
    android:usesCleartextTraffic="true"
    ... >
英文:

Use android:usesCleartextTraffic="true" on your manifest file on application.

  &lt;application
    ...
    android:usesCleartextTraffic=&quot;true&quot;
    ... &gt;

huangapple
  • 本文由 发表于 2020年5月4日 13:46:35
  • 转载请务必保留本文链接:https://java.coder-hub.com/61585857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定