【问题标题】:Android Get json response of website callAndroid获取网站调用的json响应
【发布时间】:2017-02-22 09:16:59
【问题描述】:

有些网站会调用端点并接收 json 响应。 我想知道如何在 myAndroid 应用程序中调用网站并检索他显示的 json 数据。 示例:这是一个 drivenow 站点地图

drivenow map link

如果我打开浏览器的调试模式,我会看到这个给出 josn 响应的 ajax 调用。 我想知道我可以调用这个网站并在我的 android 应用程序中获取(获取)这个响应,这样我就可以使用 json 任何的想法?帮助? 谢谢

【问题讨论】:

  • 您应该能够使用浏览器开发工具获取 Web 服务的 URL。 (您可能需要网站授权才能使用他们的网络服务)

标签: android word-wrap


【解决方案1】:

您可以使用两种方式执行 GET/POST 请求。

一些 3rd 方网络请求库

我建议使用 robospice。使用 robospice 你执行一个网络请求并给它一个 POJO。有关 POJO 的更多信息,请参阅下面的链接

https://github.com/stephanenicolas/robospice/wiki/Starter-Guide

What is RoboSpice Library in android

使用原生 Android/Java 代码

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

char[] buffer = new char[1024];

String jsonString = new String();

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

jsonString = sb.toString();

System.out.println("JSON: " + jsonString);

return new JSONObject(jsonString);}

然后像这样使用它:

try{
  JSONObject jsonObject = getJSONObjectFromURL(String urlString);

  // Parse your json here

} catch (IOException e) {
  e.printStackTrace();
} catch (JSONException e) {
  e.printStackTrace();
}

不要忘记在清单中添加 Internet 权限

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

有关解析 JSON 的更多信息,请访问 How to parse JSON in Android

注意

如果您使用第三方库,则无需手动解析 json。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多