I need to get JSON out of server response. I use WebView.loadUrl() and get HTML page with JSON in body in response. It shows in webView, but how can I access it from the code?
UPDATE: Important notice, I have dynamic URL.
I need to get JSON out of server response. I use WebView.loadUrl() and get HTML page with JSON in body in response. It shows in webView, but how can I access it from the code?
UPDATE: Important notice, I have dynamic URL.
I think that you don't need a WebView
for that. You have to use a HTTP Client for requesting the server.
A good one is OkHttp or you can use only Android-Stuff, check the doc.
If you realy would like to use a WebView
, check this answer.
You can make a request to a server and give it your APP ID via a JSONObject (or whatever it requires). I'm pretty sure you don't need a WebView to accomplish this. Here's an example of some code I used for a similar operation. Here, I stored a device ID as well as some other access credentials in a JSONObject. I then pass that to a server to request a response, I then receive a JSON response in a plain String format.
//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