当前位置:  开发笔记 > 前端 > 正文

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

如何解决《如何在android中发送HttpRequest并获取Json响应?》经验,为你挑选了2个好方法。

我想使用wp-api插件为我的wordpress网站构建一个Android应用程序.我如何在Json中发送HttpRequest(GET)和recive响应?



1> Asad Haider..:

使用此函数从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权限

然后像这样使用它:

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


不错的解决方案,不需要导入apache http客户端!

2> Ijas Ahamed ..:

尝试以下代码从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只需在`defaultConfig`上方的`android`块中的app level level build.gradle文件中添加`useLibrary'org.apache.http.legacy'.
推荐阅读
携手相约幸福
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有