<分区>
我想使用 wp-api 为我的 wordpress 网站构建一个安卓应用程序插入。我如何发送 HttpRequest(GET) 并在 Json 中接收响应?
<分区>
我想使用 wp-api 为我的 wordpress 网站构建一个安卓应用程序插入。我如何发送 HttpRequest(GET) 并在 Json 中接收响应?
最佳答案
使用此函数从 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);
}
不要忘记在 list 中添加 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();
}
关于android - 如何在 android 中发送 HttpRequest 并获取 Json 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34691175/
相关文章:
java - Android,将已经开始的 Activity 带回到前面
python - 如何在Python中将unicode转换为datetime?
php - 通过 JSON 数组/对象返回 MYSQL 查询结果?
机器人 : is constraint layout support RTL
java - 在 Android 中使用 HttpPost 发送 Bearer Token
android - 在带有 Eclipse 的 android 上使用 gdb 调试 native 代码 (C++)。是否可以?
python - Pandas Dataframe 到嵌套 JSON