org.apache.http.entity.FileEntity is deprecated in Android 6 (Marshmallow)

If you change your compileSdkVersion to 21, your app will compile cleanly. That being said, there are reasons why Google is backing away from the built-in HttpClient implementation, so you probably should pursue some other library. That “some other library” could be: the built-in classic Java HttpUrlConnection, though as you have found, its API leaves … Read more

Connecting to remote URL which requires authentication using Java

You can set the default authenticator for http requests like this: Authenticator.setDefault (new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication (“username”, “password”.toCharArray()); } }); Also, if you require more flexibility, you can check out the Apache HttpClient, which will give you more authentication options (as well as session support, etc.)

Sending files using POST with HttpURLConnection

I have no idea why the HttpURLConnection class does not provide any means to send files without having to compose the file wrapper manually. Here’s what I ended up doing, but if someone knows a better solution, please let me know. Input data: Bitmap bitmap = myView.getBitmap(); Static stuff: String attachmentName = “bitmap”; String attachmentFileName … Read more

How to add parameters to HttpURLConnection using POST using NameValuePair

You can get output stream for the connection and write the parameter query string to it. URL url = new URL(“http://yoururl.com”); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod(“POST”); conn.setDoInput(true); conn.setDoOutput(true); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(“firstParam”, paramValue1)); params.add(new BasicNameValuePair(“secondParam”, paramValue2)); params.add(new BasicNameValuePair(“thirdParam”, paramValue3)); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new … Read more

How to use java.net.URLConnection to fire and handle HTTP requests

First a disclaimer beforehand: the posted code snippets are all basic examples. You’ll need to handle trivial IOExceptions and RuntimeExceptions like NullPointerException, ArrayIndexOutOfBoundsException and consorts yourself. In case you’re developing for Android instead of Java, note also that since introduction of API level 28, cleartext HTTP requests are disabled by default. You are encouraged to … Read more