【问题标题】:how to send HttpRequest and get Json response in android? [duplicate]如何在android中发送HttpRequest并获取Json响应? [复制]
【发布时间】:2016-01-09 08:05:59
【问题描述】:

我想使用wp-api 插件为我的wordpress 网站构建一个android 应用程序。我如何发送 HttpRequest(GET) 并在 Json 中接收响应?

【问题讨论】:

标签: android json httprequest wp-api


【解决方案1】:

使用此函数从 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();
}

【讨论】:

  • 不错的解决方案,不需要导入apache http客户端!
  • 这里至少有两个主要错误。 1.urlConnection.setDoOutput(true);将请求更改为POST方法。 2. 它有效地执行了两个请求,new InputStreamReader(url.openStream() 再次打开url,而忽略了urlConnection 及其所有属性。 3.sb.append(line + "\n")构造一个多余的String
【解决方案2】:

尝试下面的代码从 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" );
}

【讨论】:

  • 在哪里可以找到 HttpClient?我必须包含什么包裹?
  • @Tarion 只需在您的应用级 build.gradle 文件中添加 android defaultConfig 块上方的useLibrary 'org.apache.http.legacy'
  • 这是一种已弃用的方法。 Android Studio 会给你警告。考虑将 volley 用于网络请求。见developer.android.com/training/volley/simple
【解决方案3】:
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();
        }

【讨论】:

    猜你喜欢
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多