I have used only DefaultHttpClient for WebService call in my apps.
But as DefaultHttpClient is deprecated i am confused that what to use.
I want to choose the best among them for my further development.
Also suggest me if any other best way to call WebServices.
DefaultHttpClient is kind of Apache Library that still used but nowadays, HttpURLConnection borns and it's recommend by google because it's more suitable for mobile application than Apache Library. DefaultHttpClient also can be used out of android environment, but in android, it's deprecated and we should use HttpUrlConnection with many advantages: good for limit android memory, good for battery ...
It would find it not too difficult to use, below is some pieces of code that can be useful
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(CONNECT_TIME_OUT);
connection.setReadTimeout(READ_TIME_OUT);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + CHARSET);
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParams.getBytes().length));
if (headers != null) addHeaderFields(connection, headers);
if (!TextUtils.isEmpty(urlParams)) {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), CHARSET), true);
writer.append(urlParams);
writer.flush();
writer.close();
}
StringBuilder response = new StringBuilder();
// checks server's status code first
int status = connection.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
connection.disconnect();
} else {
throw new ApiException(ApiException.APP_EXCEPTION, "Server returned non-OK status: " + status);
}
return response.toString();
As Android have deprecated DefaultHTTPClient Class and methods.
Android 6.0 release removes support for the Apache HTTP client. If your app is using this client and targets Android 2.3 (API level 9) or higher, use the HttpURLConnection class instead. This API is more efficient because it reduces network use through transparent compression and response caching, and minimizes power consumption.
To continue using the Apache HTTP APIs, you must first declare the following compile-time dependency in your build.gradle file:
android {
useLibrary 'org.apache.http.legacy'
}
Here is URL from where you can have more details about HttpURLConnection.
https://developer.android.com/reference/java/net/HttpURLConnection.html
DefaultHTTPClient is deprecated in android and will no longer be supported in Marshmallow (Android 6.0) and the API's after it. HTTPURLConnection is preferred over HTTPClient.
For networking operations I would recommend you to use Volley , Android's official networking related well tuned library. It eases the way network calls are made and is faster plus it's operations are asynchronous by default (you don't need to worry about custom threads for network calls).
Here is a good tutorial to use Volley : Android working with Volley Library
Android guide for Volley : Transmitting Network Data Using Volley
Related
Does HttpURLConnection that works for android API 23 also work for android API22?
I'm trying to program for android version over 4.0.
I am unsure if the difference between sdk22 and sdk23 will cause a problem
// http client
URL url = new URL(url1);
HttpURLConnection httpClient = (HttpURLConnection) url.openConnection();
httpClient.setRequestMethod("POST");
httpClient.setUseCaches(false);
httpClient.setDoInput(true);
httpClient.setDoOutput(true);
httpClient.setRequestProperty("Connection", "Keep-Alive");
httpClient.addRequestProperty("Content-length", reqEntity.getContentLength() + "");
OutputStream os = httpClient.getOutputStream();
reqEntity.writeTo(httpClient.getOutputStream());
os.close();
httpClient.connect();
if (httpClient.getResponseCode() == HttpURLConnection.HTTP_OK) {
return readStream(httpClient.getInputStream());
Yes it will work without any issues, and the difference will not cause any problem
HttpUrlConnection is available in from API Level 1 , you can further get more insight from the docs.
Its a good practice to use HttpUrlConnection over deprecated Apache HttpClient classes,
This question already has an answer here:
JSONParser from androidhive tutorial, NoSuchMethodError in DefaultHttpClient
(1 answer)
Closed 7 years ago.
I've been searching a lot, however haven't find any solution. I want to use URL, HttpsUrlConnection instead of deprecated ones (HttpClient, HttpPost, DefaultHttpClient). I have this code below so far:
Note "MyUrl" takes some parameters. See question 2.
URL url = new URL("MyUrl");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
/*Here exception occurs!*/
connection.connect();
So, I have 2 problems to solve: (Maybe the 2nd one should be solved 1stly. I have no idea...)
When I use connection.someMethod(); SSLException occurs. (i.e connection.getResponseCode();)
The Error is :
javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x635cb550: Failure in SSL library, usually a protocol error
What is alternative way of List<NameValuePair> & BasicNameValuePair ? Those are deprecated as well.
You can use following library for HTTP requests-response
http://loopj.com/android-async-http/
http://square.github.io/okhttp/
http://developer.android.com/training/volley/index.html
You can use Google-Gson for parsing JSON data
https://github.com/google/gson
You don't need to use connect. Simply doing this:
conn.setRequestMethod("POST");
InputStream in = new BufferedInputStream(conn.getInputStream());
response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
You will get your response.
Also, you can use ContentValues as a replacement for NameValuePair:
ContentValues initialValues = new ContentValues();
initialValues.put("parameter", value);
How can I receive Pushbullet notes/images/profile details via API-Key on Android? My main problem is the SSL security in that point. (BTW: I'm pretty much a beginner in Android and only know the basics.)
The auth looks like this:
https://apikey#api.pushbullet.com/v2/users/me
I'm successfully requesting the content of a webpage (e.g. wikipedia.org) via
try {
URL url = new URL("https://www.wikipedia.org");
URLConnection urlConnection = url.openConnection();
InputStream in = urlConnection.getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(in, writer);
theString = writer.toString();
textView.setText(theString);
} catch (Exception e) {
textView.setText("Error: "+e "String content: " +theString);
}
but when I'm requesting, for example, my profile details I'm always getting a
javaio FileNotFoundException
If you run your requests through https://www.runscope.com you can often see what the request is that your client is actually making (they have a free plan for trying it out).
If I had to guess I would say it's likely the authorization is not working correctly. Are you able to get that page using curl? It should look something like:
curl -u <apikey>: https://api.pushbullet.com/v2/users/me
Assuming that works, try something like
urlConnection.setRequestProperty("Authorization", "Bearer <apikey>");
or however it is you set headers on your HTTP requests. This is more explicit than relying on the https://password#domain url thing.
I'm trying to PUT some XML to a server, but the gist of it is that no matter what I do, HttpPut simply won't put anything in the Http body. The server always comes back saying that the body is missing, and looking at it through Wireshark, nothing is there! Here's the code I'm using to set up and run the request:
HttpPut putRequest = new HttpPut(urlString]);
StringEntity stringEntity = new StringEntity(xmlString, HTTP.ISO_8859_1);
stringEntity.setContentType("text/xml");
putRequest.setEntity(stringEntity);
putRequest.addHeader("Host", formatUrlForHostHeader(broadsoftUrl));
putRequest.addHeader("Authorization", authorizationString);
putRequest.addHeader("Content-Type", "text/xml");
putRequest.addHeader("Accept", "text/xml");
response = httpClient.execute(putRequest);
I'm not sure what else to include here. I tried it on 4.2 and 4.0.3. This code is running in the doInBackground of an AsyncTask. The response code I get is a 409 Conflict, and the body is the server's application-specific message, telling me the body is missing. I confirmed that it's missing with Wireshark.
EDIT:
An interesting note is that I ran the same code standalone on my desktop, and it worked. So, is there something up with the Android versions of HttpClient, or the system? I tried a few different API levels, too, just to check.
Any thoughts?
Thanks!
Alright, so the solution was to just give up on HttpPut and all that, and use HttpURLConnection. Here's how we ended up doing it:
URL url = new URL(theUrl);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty("Host", formatUrlForHostHeader(broadsoftUrl));
httpCon.setRequestProperty("Authorization", authorizationString);
httpCon.setRequestProperty("Content-Type", "text/xml; charset=ISO_8859_1");
httpCon.setRequestProperty("Accept", "text/xml");
httpCon.setDoInput(true);
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream(), "ISO_8859_1");
out.write(xmlData);
out.close();
if(httpCon.getErrorStream() == null) {
return "";
} else {
return "ERROR";
}
We didn't need to get the response from our PUT request, but you check if it failed by seeing if the error stream exists. If you wanted to get the response, you would do something like this:
StringWriter writer = new StringWriter();
IOUtils.copy(httpCon.getInputStream(), writer, encoding);
String responseString = writer.toString();
Of course, you would have to include Apache's IOTools in your app.
409 Conflict is usually an Edit Conflict error, usually associated with wikis, but it could be any type of conflict with the request.
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
What type of data are you trying to post and is it possible that the host has existing data that cannot be changed?
I have an Android app that works fine with Android 2.x and 3.x, but it fails when run on Android 4.x.
The problem is in this section of code:
URL url = new URL("http://blahblah.blah/somedata.xml");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
When the application is running on Android 4.x, the getInputStream() call results in a FileNotFoundException. When the same binary is running on earlier versions of Android, it succeeds. The URLs also work fine in web browsers and with curl.
Apparently something about HttpURLConnection has changed in ICS. Does anybody have any idea what has changed, and/or what the fix might be?
Try removing the setDoOutput call. Taken from this blog:
a blog
Edit: This is needed when using a POST call.
A FileNotFoundException may also been thrown if the server returns a bad error code (e.g., 400 or 401). You can handle this as follows:
int responseCode = con.getResponseCode(); //can call this instead of con.connect()
if (responseCode >= 400 && responseCode <= 499) {
throw new Exception("Bad authentication status: " + responseCode); //provide a more meaningful exception message
}
else {
InputStream in = con.getInputStream();
//etc...
}
I Don't know why, but dealing manually with redirection resolves the problem.
connection.setInstanceFollowRedirects(false);
A little late but you can also verify the accepted content. You can add this line to accept all kinds of contents
urlConnection.setRequestProperty("Accept","*/*");