This question already has an answer here:
-
Simple parse JSON from URL on Android and display in listview
7 answers
I want to access a webservice function that takes two strings as arguments and return a JSON value. I found a solution to do this using volley library but apparently i have to use Android Lolipop for this.
is there a way to do this without volley? Another library? or httpconnection?
An example of this use will be perfect.
You can use a library http://square.github.io/retrofit/
or using httpURLConnection
HttpURLConnection httpURLConnection = null;
try {
// create URL
URL url = new URL("http://example.com");
// open connection
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
// 15 seconds
httpURLConnection.setConnectTimeout(15000);
Uri.Builder builder = new Uri.Builder().appendQueryParameter("firstParameter", firsParametersValue).appendQueryParameter("secondParameter", secondParametersValue)
String query = builder.build().getEncodedQuery();
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
bufWriter.write(query);
bufWriter.flush();
bufWriter.close();
outputStream.close();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
StringBuilder response = new StringBuilder();
BufferedReader input = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()), 8192);
String strLine = null;
while ((strLine = input.readLine()) != null) {
response.append(strLine);
}
input.close();
Object dataReturnedFromServer = new JSONTokener(response.toString()).nextValue();
// do something
// with this
}
} catch (Exception e) {
// do something
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();// close connection
}
}