如何从具有动态URL的Webview获取JSON?

3
我需要从服务器响应中获取JSON。我使用WebView.loadUrl()并获得带有JSON的HTML页面作为响应主体。它显示在webView中,但是我如何从代码中访问它?
更新:重要通知,我有动态URL。

你为什么要使用 WebView? - Blackbelt
你需要使用 WebView 显示页面的原因是什么?如果你直接使用 HttpURLConnection 获取响应,那么很容易从响应中获取 JSON。 - NoChinDeluxe
我使用WebView是因为我连接到API,该API请求我的应用程序ID + 我需要首先从中打开一个网页。 - aleien
2个回答

1
我认为你不需要使用 WebView。你需要使用 HTTP Client 来请求服务器。
一个很好的选择是 OkHttp,或者你可以只使用 Android-Stuff,查看 doc
如果你真的想使用 WebView,请查看这个 answer

谢谢你的回答!我会立即尝试。 另外,我可以使用Retrofit获取JSON吗? - aleien
是的,你可以。JSON只是一些文本。之后,你应该使用一个库来轻松读取JSON,比如谷歌的GSON,参见https://dev59.com/UnE85IYBdhLWcg3w1HKF#31743324。 - Kevin Robatel
由于我使用了动态URL,似乎我不能依赖Retrofit。但是JavaScript方法完美地解决了问题,谢谢! - aleien

0

您可以向服务器发出请求并通过 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接