Parse JSON from HttpURLConnection object
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.
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
And then you can use returned string with Google Gson to map JSON to object of specified class, like this:
String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);
There is a sample of AuthMsg class:
public class AuthMsg {
private int code;
private String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
JSON returned by http://localhost/authmanager.php must look like this:
{"code":1,"message":"Logged in"}
Regards
Java HttpURLConnection Returns JSON
You can use Gson. Here is the code to help you:
Map<String, Object> jsonMap;
Gson gson = new Gson();
Type outputType = new TypeToken<Map<String, Object>>(){}.getType();
jsonMap = gson.fromJson("here your string", outputType);
Now you know how to get from and put those in session. You need to include Gson library in classpath.
How to get JSON object using HttpURLConnection instead of Volley?
The url in JsonObjectRequest()
is not optional, and the JSONObject parameter is used to post parameters with the request to the url.
From the documentation:
http://afzaln.com/volley/com/android/volley/toolbox/JsonObjectRequest.html
http://developer.android.com/training/volley/index.html
JsonObjectRequest
public JsonObjectRequest(int method,
String url,
JSONObject jsonRequest,
Response.Listener listener,
Response.ErrorListener errorListener) Creates a new request.Parameters:
method - the HTTP method to use
url - URL to fetch the JSON from
jsonRequest - A JSONObject to post with the request. Null is allowed
and indicates no parameters will be posted along with request.listener - Listener to receive the JSON response
errorListener - Error listener, or null to ignore errors.
Using HttpURLConnection
:
http://developer.android.com/reference/java/net/HttpURLConnection.html
The code would be something like this:
public class getData extends AsyncTask<String, String, String> {
HttpURLConnection urlConnection;
@Override
protected String doInBackground(String... args) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL("https://api.github.com/users/dmnugent80/repos");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result.toString();
}
@Override
protected void onPostExecute(String result) {
//Do something with the JSON string
}
}
How to retrieve JSON from my method?
You should read from the InputStream
:
JSONObject myData = new JSONObject(IOUtils.toString(connection.getInputStream(),
connection.getContentEncoding());
IOUtils
is a class from the Apache Commons IO utility library.
How use GET request with web API for JSON response using HttpURLConnection?
Just use an AsyncTask subclass in order to do the network operation inside thedoInBackground()
method override, which is run on a background thread. Then pass the result to the onPostExecute()
method override, which is run on the UI thread.
Here is a simple Activity with an AsyncTask that does what you need:
public class TestActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
textView = (TextView) findViewById(R.id.textView);
new NetworkConnect().execute();
}
class NetworkConnect extends AsyncTask<Void, Void, JSONObject> {
private static final String JSON_URL = "http://ip.jsontest.com/";
String charset = "UTF-8";
HttpURLConnection conn;
StringBuilder result;
URL urlObj;
@Override
protected JSONObject doInBackground(Void... args) {
JSONObject retObj = null;
try {
urlObj = new URL(JSON_URL);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("NetworkConnect", "result: " + result.toString());
retObj = new JSONObject(result.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return retObj;
}
@Override
protected void onPostExecute(JSONObject json) {
//Use JSON result to display in TextView
if (json != null) {
textView.setText(json.toString());
}
}
}
}
Note: ensure that you have the INTERNET permission in the AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
get JSONObject from httpURLConnection and parsing into ArrayList
First problem which type would be the choice for doInBackground
function
JSON String as in post is JSONArray
of JSONObject's
instead of JSONObject
. create JSONArray
from result
in doInBackground
:
JSONArray jsonArray = new JSONArray(result.toString());
how to deliver the jsonObject to my function onPostExecute?
Instead of JSONObject
return ArrayList
of items.
how can I get the content of the jsonObject variable to my ArrayList?
Parse jsonArray
to get all JSONObject's from it then get required value from each JSONObject
and add it to listdata
ArrayList<String> listdata = new ArrayList<String>();
for(int n = 0; n < jsonArray.length(); n++)
{
JSONObject object = jsonArray.getJSONObject(n);
listdata.add(object.optString("nr"));
}
return listdata;
Post Json data with HttpURLConnection to REST API server
This is how I send a POST
Let me know if you need any clarification.
public static String executePost(String targetURL, String requestJSON, String apikey) {
HttpURLConnection connection = null;
InputStream is = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
//TODO may be prod or preprod api key
if (apikey.equals(Constants.APIKEY_PREPROD)) {
connection.setRequestProperty("Authorization", Constants.APIKEY_PREPROD);
}
if (apikey.equals(Constants.APIKEY_PROD)){
connection.setRequestProperty("Authorization", Constants.APIKEY_PROD);
}
connection.setRequestProperty("Content-Length", Integer.toString(requestJSON.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
System.out.println(requestJSON);
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(requestJSON);
wr.close();
//Get Response
try {
is = connection.getInputStream();
} catch (IOException ioe) {
if (connection instanceof HttpURLConnection) {
HttpURLConnection httpConn = (HttpURLConnection) connection;
int statusCode = httpConn.getResponseCode();
if (statusCode != 200) {
is = httpConn.getErrorStream();
}
}
}
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
Related Topics
A Simple Scenario Using Wait() and Notify() in Java
How to Ignore Ssl Certificate Errors in Apache Httpclient 4.0
Similarity String Comparison in Java
When Do Java Generics Require <? Extends T> Instead of <T> and Is There Any Downside of Switching
Is System.Nanotime() Completely Useless
Convert Iterable to Stream Using Java 8 Jdk
How to Compare Two Version Strings in Java
How to Use 3Des Encryption/Decryption in Java
Remove All Occurrences of Char from String
Error: Selection Does Not Contain a Main Type
In Java, How to Write a String Literal Without Having to Escape Quotes
Java Filewriter with Append Mode