如何在Android中发送HttpRequest并获取Json响应?

14

我想使用WP-API插件为我的WordPress网站构建一个Android应用程序。如何发送GET请求并接收JSON响应?


1
http://developer.android.com/training/volley/index.html - Itzik Samara
你可以使用这个:https://dev59.com/OGoy5IYBdhLWcg3wScFB#8655039 - user1140237
3个回答

31

使用此函数从URL获取JSON。

public static JSONObject getJSONObjectFromURL(String urlString) throws IOException, JSONException {
    HttpURLConnection urlConnection = null;
    URL url = new URL(urlString);
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setReadTimeout(10000 /* milliseconds */ );
    urlConnection.setConnectTimeout(15000 /* milliseconds */ );
    urlConnection.setDoOutput(true);
    urlConnection.connect();

    BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
    StringBuilder sb = new StringBuilder();

    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line + "\n");
    }
    br.close();

    String jsonString = sb.toString();
    System.out.println("JSON: " + jsonString);

    return new JSONObject(jsonString);
}

在你的清单文件中不要忘记添加Internet权限。

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

然后像这样使用:

try{
      JSONObject jsonObject = getJSONObjectFromURL(urlString);
      //
      // Parse your json here
      //
} catch (IOException e) {
      e.printStackTrace();
} catch (JSONException e) {
      e.printStackTrace();
}

2
不错的解决方案,不需要导入Apache HTTP客户端! - RestingRobot
这里至少有两个主要错误。1. urlConnection.setDoOutput(true); 将请求更改为 POST 方法。2. 它实际上执行了两个请求,new InputStreamReader(url.openStream() 再次打开 url,忽略了 urlConnection 和它的所有属性。3. sb.append(line + "\n") 构造了一个多余的 String - Victor Sergienko

14

尝试以下代码从URL获取JSON

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget= new HttpGet(URL);

HttpResponse response = httpclient.execute(httpget);

if(response.getStatusLine().getStatusCode()==200){
   String server_response = EntityUtils.toString(response.getEntity());
   Log.i("Server response", server_response );
} else {
   Log.i("Server response", "Failed to get server response" );
}

3
HttpClient在哪里找?我需要包括哪个软件包? - Tarion
2
@Tarion 只需在您的应用级 build.gradle 文件中,在 android 块上方的 defaultConfig 之上添加 useLibrary 'org.apache.http.legacy' 即可。 - Mohammedsalim Shivani
这是一个已弃用的方法。Android Studio会对此发出警告。考虑使用Volley进行网络请求。请参见https://developer.android.com/training/volley/simple。 - kPieczonka

0
try {
            String line, newjson = "";
            URL urls = new URL(url);
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(urls.openStream(), "UTF-8"))) {
                while ((line = reader.readLine()) != null) {
                    newjson += line;
                    // System.out.println(line);
                }
                // System.out.println(newjson);
                String json = newjson.toString();
               JSONObject jObj = new JSONObject(json);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接