我需要从服务器响应中获取JSON。我使用WebView.loadUrl()并获得带有JSON的HTML页面作为响应主体。它显示在webView中,但是我如何从代码中访问它?
更新:重要通知,我有动态URL。
更新:重要通知,我有动态URL。
您可以向服务器发出请求并通过 JSONObject(或其他所需方式)提供您的应用程序 ID。我很确定您不需要 WebView 来完成此操作。以下是我为类似操作使用的一些代码示例。在这里,我将设备 ID 以及一些其他访问凭据存储在 JSONObject 中。然后,我将其传递给服务器请求响应,然后我会以纯字符串格式收到 JSON 响应。
//open connection to the server
URL url = new URL("your_url");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//set request properties
httpURLConnection.setDoOutput(true); //defaults request method to POST
httpURLConnection.setDoInput(true); //allow input to this HttpURLConnection
httpURLConnection.setRequestProperty("Content-Type", "application/json"); //header params
httpURLConnection.setRequestProperty("Accept", "application/json"); //header params
httpURLConnection.setFixedLengthStreamingMode(jsonToSend.toString().getBytes().length); //header param "content-length"
//open output stream and POST our JSON data to server
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
outputStreamWriter.write(jsonToSend.toString()); //whatever you're sending to the server
outputStreamWriter.flush(); //flush the stream when we're finished writing to make sure all bytes get to their destination
//prepare input buffer and get the http response from server
StringBuilder stringBuilder = new StringBuilder();
int responseCode = httpURLConnection.getResponseCode();
//Check to make sure we got a valid status response from the server,
//then get the server JSON response if we did.
if(responseCode == HttpURLConnection.HTTP_OK) {
//read in each line of the response to the input buffer
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"utf-8"));
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
//You've now got the JSON, which can be accessed just as a
//String -- stringBuilder.toString() -- or converted to a JSONObject
bufferedReader.close(); //close out the input stream
HttpURLConnection
获取响应,那么很容易从响应中获取 JSON。 - NoChinDeluxe