我需要从服务器响应中获取JSON。 我使用WebView.loadUrl()并在主体中获取带有JSON的HTML页面作为响应。它在webView中显示,但我如何从代码中访问它?
更新:重要提示,我有动态网址。
答案 0 :(得分:1)
我认为你不需要WebView
。您必须使用HTTP客户端来请求服务器。
好的是OkHttp或者您只能使用Android-Stuff,请查看doc。
如果您真的想使用WebView
,请检查此answer。
答案 1 :(得分:0)
您可以向服务器发出请求,并通过JSONObject(或其所需的任何内容)为其提供您的APP ID。我很确定你不需要WebView来实现这一目标。这是我用于类似操作的一些代码的示例。在这里,我在JSONObject中存储了设备ID以及一些其他访问凭证。然后我将它传递给服务器以请求响应,然后我以普通的String格式接收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