I am doing basic http auth with the HttpURLConnection
object in Java.
URL urlUse = new URL(url);
HttpURLConnection conn = null;
conn = (HttpURLConnection) urlUse.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-length", "0");
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setConnectTimeout(timeout);
conn.setReadTimeout(timeout);
conn.connect();
if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
{
success = true;
}
I am expecting a JSON object, or string data in the format of a valid JSON object, or HTML with simple plain text that is valid JSON. How do I access that from the HttpURLConnection
after it returns a response?
Define the following function (not mine, not sure where I found it long ago):
}
Then:
The JSON string will just be the body of the response you get back from the URL you have called. So add this code
That will allow you to see the JSON being returned to the console. The only missing piece you then have is using a JSON library to read that data and provide you with a Java representation.
Here's an example using JSON-LIB
In addition, if you wish to parse your object in case of http error (400-5** codes), You can use the following code: (just replace 'getInputStream' with 'getErrorStream':
You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.
And then you can use returned string with Google Gson to map JSON to object of specified class, like this:
There is a sample of AuthMsg class:
JSON returned by http://localhost/authmanager.php must look like this:
Regards
This function will be used get the data from url in form of HttpResponse object.
Above function is called here and we receive a String form of the json using the Apache library Class.And in following statements we try to make simple pojo out of the json we received.
This is a simple java model class for incomming json. public class JsonJavaModel{ String content; String title; } This is a custom deserialiser:
Include Gson library and org.apache.http.util.EntityUtils;