Get JSON from URL - deprecated method? - android

I have been using this code to get JSON from a specified URL, but today I checked it, and everything in it is deprecated. It still works fine, but I want to know what is the new method of doing it?
Here's what I have:
#Override
protected String doInBackground(String... params) {
try {
HttpClient client = new DefaultHttpClient();
StringBuilder url = new StringBuilder("some url");
HttpGet hg = new HttpGet(url.toString());
HttpResponse hr = client.execute(hg);
int status = hr.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity he = hr.getEntity();
String data = EntityUtils.toString(he);
jsonGet = new JSONObject(data);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
The deprecated objects are HttpClient, HttpGet, HttpResponse, HttpEntity and EntityUtils.
EDIT: As suggested in some questions, this way
HttpClient client = HttpClientBuilder.create().build();
does not work for me, as I am getting HttpClientBuilder cannot be resolved

Apache httpClient is deprecated with api level 22 you can read it about this blog.
there is a new client for android now and it is very good.
but you can use okhttp instead (also back compat is possible).
EDIT
check this link(URL.openConnection()). this blog was posted in 2011 but they mentioned the deprecation there first as far as i know.

First of all you have to search well on Google.
Here is your answer may it will helps you.
The HttpClient documentation points you in the right direction:
org.apache.http.client.HttpClient:
This interface was deprecated in API level 22.
Please use openConnection() instead. Please visit this webpage for further details.
means that you should switch to java.net.URL.openConnection().
Here's how you could do it:
URL url = new URL("http://some-server");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// read the response
System.out.println("Response Code: " + conn.getResponseCode());
InputStream in = new BufferedInputStream(conn.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);
IOUtils documentation: Apache Commons IO
IOUtils Maven dependency: http://search.maven.org/#artifactdetails|org.apache.commons|commons-io|1.3.2|jar
Special Thanks to fateddy for this answer

Related

javax.net.ssl.SSLPeerUnverifiedException: No peer certificate on HttpClient but works fine with HttpUrlConnection

Previously,I used HttpClient for a http post request and it was working fine, until I believe the server team made some changes. Then I kept getting
javax.net.ssl.SSLPeerUnverifiedException: No peer certificate Exception.
Then, after alot of scratching my head, I tried HttpUrlConnection and it works fine, but still I can't figure out why I got that exception while using HttpClient.
Before code was :
public String postDataAndGetStringResponse( List<NameValuePair> nameValuePairs ) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost( link );
try {
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
InputStream is = response.getEntity().getContent();
String result = "";
if (is != null) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String l = "";
while ((l = reader.readLine()) != null) {
result += l;
}
reader.close();
}
is.close();
return result;
} catch (Exception e) {
Logger.printStackTrace(e);
return ServerUnrechable;
}
}
I did check the server using https://www.sslshopper.com and everything is ticked, it would be very helpful if anybody could tell me the cause to this issue.
One of the most likely causes is that the server you're trying to use now relies on Server Name Indication.
SNI support was added a to HttpsURLConnection in Android, but not to the Apache HTTP Client bundled (now deprecated/removed). See this related question for details.

Android: Getting HTTP response incrementally like in iOS

I'm relatively new to Android (I'm an iOS-Developer) and I want to call a Webservice like I'm used to in iOS with NSURLConnectionDelegate's method
didReceiveData:(NSData *)data
I need to get the data incrementally because I'm building a streaming API that gets a lot of JSON data in response and needs to check the data for complete blocks.
Would be great if someone could help me, I've been searching for a while and didn't find a satisfying solution so far.
If you try to call web services in Android you should use the AsyncTask where the request would be made asynchronously. Have a look at the documentation. Every time you're request would be finished the method onPostExecute(Object result) would be called. Thats the method where you can go on with further processes.
The URLConnection documentation contain following example:
URL url = new URL("ftp://mirror.csclub.uwaterloo.ca/index.html");
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
try {
readStream(in);
finally {
in.close();
}
If i right understood your question, just implement readStream function as you need.
I found out how to do this with the help of a friend and some links.
You need to implement an own ResponseHandler like this:
class ChunkedResponseHandler implements ResponseHandler<String> {
#Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
StringBuffer output = new StringBuffer();
byte[] b = new byte[4096];
int n;
while ((n = stream.read(b)) != -1) {
output.append(new String(b, 0, n));
// do something while input is streaming
}
return output.toString();
}
}
Now you simply have to assign the response handler when starting the request:
HttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet("someURL");
ResponseHandler<String> responseHandler = new ChunkedResponseHandler();
String responseBody = client.execute(postRequest, responseHandler);

Android HTTP request wierd 404 not found issue

In my application, I am trying to hit a URL which I do using the following code
try {
url = new URL(serverURL);
httpURLConnection = (HttpURLConnection) url.openConnection();
int timeout = 30000;
httpURLConnection.setConnectTimeout(timeout);
httpURLConnection.setReadTimeout(timeout);
httpURLConnection.connect();
String httpResponseMessage = httpURLConnection.getResponseMessage();
responseCode = httpURLConnection.getResponseCode();
Log.i(LOG_TAG,"Response code "+responseCode);
} catch (Exception e) {
e.printStackTrace();
}
The (confidential) URL when opened through browser (on computer as well as on phone), works perfectly and the response is as expected. But when I hit the same URL via the above piece of code, it gives me response code 404 (NOT FOUND). Can anybody tell me what the issue can be?
(Sorry, can not post the URL since is highly confidential.)
Are you sure that you have the android.permission.INTERNET declared in your AndroidManifext.xml?
Problem solved :)
try {
url = new URL(serverURL);
Log.i(LOG_TAG, url+"");
HttpGet method= new HttpGet(new URI(serverURL));
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(serverURL));
HttpResponse response = client.execute(method);
responseCode = response.getStatusLine().getStatusCode();
Log.i(LOG_TAG,"Response code response "+response);
Log.i(LOG_TAG,"Response responseCode "+responseCode);
} catch (Exception e) {
e.printStackTrace();
}
Actually you don't even need following two lines in your code.
HttpGet request = new HttpGet();
request.setURI(new URI(serverURL));
One HttpGet is enough and you don't need it twice.
Not sure if this matters but I had the exact problem.
I was doing some explicity port 80 stuff and removing this line made it work:
HttpHost host = new HttpHost(targetHost, 80, "http");

etag comparision code example

I'm trying to simulate a process like "cache validation" in my application.
I will download a new version of my webapplication on the device (android-based), but I only want to download a new version of the files, based in a etag comparision.
Does anyone a example of how use the Etag mechanism in Android?
You can access the ETag field from a HttpURLConnection object such as like this:
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
String etag = conn.getHeaderField("ETag");
Of course, you will need to make sure that the server you are testing this against supports ETags.
Maybe class "HttpRequest" from this library (kevinsawicki) will help you.
For example:
File latest = new File("/data/cache.json");
HttpRequest request = HttpRequest.get("http://google.com");
//Copy response to file
request.body(latest);
//Store eTag of response
String eTag = request.eTag();
//Later you can check if changes exist
boolean unchanged = HttpRequest.get("http://google.com")
.ifNoneMatch(eTag)
.notModified();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
HttpResponse response = httpClient.execute(httpPost);
Log.d("Http Response:", response.getFirstHeader("etag").toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can refer to the specific implement of ShallowEtagHeaderFilter performing etag generation and validation in Spring.

Connecting to a webserver with android

I have to connect to a webserver from android and I have to access a webservice and a webpage from the webserver. Can anybody help me? Please give step by step process with some code snippets because I am new to android and I don't know anything in connecting to a webserver.
You can use an HttpClient:
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(uri);
HttpResponse httpResponse = httpClient.execute(httpGet);
BufferedReader reader = new BufferedReader(
new InputStreamReader(httpResponse.getEntity().getContent()));
// user reader to read & parse response
reader.close();
Parsing the response obviously depends on the format (e.g. SOAP, JSON, etc.)
You haven't given very much info (what kind of web page, XML/JSON/HTML/etc. ?). But the basic principles of regular Java apply. Using URL and InputStream:
URL url = new URL(...);
InputStream is = url.openStream();
And from there it depends what kind of data you're dealing with.
If you don't want to use an additional library, here is a means for sending an "id" and "name" to a server:
URL url = null;
try {
String registrationUrl = String.format("http://myserver/register?id=%s&name=%s", myId, URLEncoder.encode(myName,"UTF-8"));
url = new URL(registrationUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
Log.d("MyApp", "Registration success");
} else {
Log.w("MyApp", "Registration failed for: " + registrationUrl);
}
} catch (Exception ex) {
ex.printStackTrace();
}
You could just as easily send other data via this URI "GET" style, but if you need to send something more detailed a POST will be required.
Note: Originally posted to answer a similar question here: How to connect android to server

Categories

Resources