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

如何在android中发送HttpRequest并获得Json响应?,android,json,httprequest,wp-api,Android,Json,Httprequest,Wp Api,我想使用插件为我的wordpress网站构建一个android应用程序。如何在Json中发送HttpRequest(GET)和recive响应 使用此函数从URL获取JSON try { String line, newjson = ""; URL urls = new URL(url); try (BufferedReader reader = new BufferedReader(new InputStreamReade

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

使用此函数从URL获取JSON

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();
        }
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();
}

尝试以下代码从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只需将
useLibrary'org.apache.http.legacy'
添加到
android
上面的
defaultConfig
块中的应用程序级build.gradle文件中。这是一种不推荐使用的方法。Android studio将就此向您发出警告。考虑使用截击网络请求。请参阅尼斯解决方案,它不需要导入apache http客户端!这里至少有两个主要错误。1. <代码>urlConnection.setDoOutput(true)将请求更改为
POST
方法。2.它有效地执行两个请求,
newInputStreamReader(url.openStream()
再次打开
url
,忽略
urlConnection
及其所有属性。3.
sb.append(line+“\n”)
构造了一个多余的
字符串。