In order to create a new Android HTTP Client HttpURLConnection, call openConnection() on a URL instance. Since openConnection() returns a URLConnection, you need to explicitly cast the returned value.
URL url =newURL("http://example.com");HttpURLConnection connection =(HttpURLConnection) url.openConnection();// do something with the connection
If you are creating a new URL, you also have to handle the exceptions associated with URL parsing.
try{URL url =newURL("http://example.com");HttpURLConnection connection =(HttpURLConnection) url.openConnection();// do something with the connection}catch(MalformedURLException e){
e.printStackTrace();}
Once the response body has been read and the connection is no longer required, the connection should be closed by calling disconnect().
Here is an example:
URL url =newURL("http://example.com");HttpURLConnection connection =(HttpURLConnection) url.openConnection();try{// do something with the connection}finally{
connection.disconnect();}
Sending an HTTP GET request
URL url =newURL("http://example.com");HttpURLConnection connection =(HttpURLConnection) url.openConnection();try{BufferedReader br =newBufferedReader(newInputStreamReader(connection.getInputStream()));// read the input stream// in this case, I simply read the first line of the streamString line = br.readLine();Log.d("HTTP-GET", line);}finally{
connection.disconnect();}
Please note that exceptions are not handled in the example above. A full example, including (a trivial) exception handling, would be:
URL url;HttpURLConnection connection =null;try{
url =newURL("http://example.com");
connection =(HttpURLConnection) url.openConnection();BufferedReader br =newBufferedReader(newInputStreamReader(connection.getInputStream()));// read the input stream// in this case, I simply read the first line of the streamString line = br.readLine();Log.d("HTTP-GET", line);}catch(IOException e){
e.printStackTrace();}finally{if(connection !=null){
connection.disconnect();}}
Reading the body of an HTTP GET request
URL url =newURL("http://example.com");HttpURLConnection connection =(HttpURLConnection) url.openConnection();try{BufferedReader br =newBufferedReader(newInputStreamReader(connection.getInputStream()));// use a string builder to bufferize the response body// read from the input strea.StringBuilder sb =newStringBuilder();String line;while((line = br.readLine())!=null){
sb.append(line).append('\n');}// use the string builder directly,// or convert it into a StringString body = sb.toString();Log.d("HTTP-GET", body);}finally{
connection.disconnect();}
Please note that exceptions are not handled in the example above.
Sending an HTTP POST request with parameters
Use a HashMap to store the parameters that should be sent to the server through POST parameters:
HashMap<String,String> params;
Once the params HashMap is populated, create the StringBuilder that will be used to send them to the server:
StringBuilder sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
Then, create the HttpURLConnection, open the connection, and send the POST parameters:
Then receive the result that the server sends back:
try{InputStream in =newBufferedInputStream(conn.getInputStream());BufferedReader reader =newBufferedReader(newInputStreamReader(in));StringBuilder result =newStringBuilder();String line;while((line = reader.readLine())!=null){
result.append(line);}Log.d("test","result from server: "+ result.toString());}catch(IOException e){
e.printStackTrace();}finally{if(conn !=null){
conn.disconnect();}}
Use HttpURLConnection for multipart/form-data
Create custom class for calling multipart/form-data HttpURLConnection request
MultipartUtility.java
publicclassMultipartUtility{privatefinalString boundary;privatestaticfinalString LINE_FEED ="\r\n";privateHttpURLConnection httpConn;privateString charset;privateOutputStream outputStream;privatePrintWriter writer;/**
* This constructor initializes a new HTTP POST request with content type
* is set to multipart/form-data
*
* @param requestURL
* @param charset
* @throws IOException
*/publicMultipartUtility(String requestURL,String charset)throwsIOException{this.charset = charset;// creates a unique boundary based on time stamp
boundary ="==="+System.currentTimeMillis()+"===";URL url =newURL(requestURL);
httpConn =(HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);// indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type","multipart/form-data; boundary="+ boundary);
outputStream = httpConn.getOutputStream();
writer =newPrintWriter(newOutputStreamWriter(outputStream, charset),true);}/**
* Adds a form field to the request
*
* @param name field name
* @param value field value
*/publicvoidaddFormField(String name,String value){
writer.append("--"+ boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\""+ name +"\"").append(LINE_FEED);
writer.append("Content-Type: text/plain; charset="+ charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();}/**
* Adds a upload file section to the request
*
* @param fieldName name attribute in <input type="file" name="..." />
* @param uploadFile a File to be uploaded
* @throws IOException
*/publicvoidaddFilePart(String fieldName,File uploadFile)throwsIOException{String fileName = uploadFile.getName();
writer.append("--"+ boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\""+ fieldName
+"\"; filename=\""+ fileName +"\"").append(LINE_FEED);
writer.append("Content-Type: "+URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();FileInputStream inputStream =newFileInputStream(uploadFile);byte[] buffer =newbyte[4096];int bytesRead =-1;while((bytesRead = inputStream.read(buffer))!=-1){
outputStream.write(buffer,0, bytesRead);}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();}/**
* Adds a header field to the request.
*
* @param name - name of the header field
* @param value - value of the header field
*/publicvoidaddHeaderField(String name,String value){
writer.append(name +": "+ value).append(LINE_FEED);
writer.flush();}/**
* Completes the request and receives response from the server.
*
* @return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* @throws IOException
*/publicList<String>finish()throwsIOException{List<String> response =newArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--"+ boundary +"--").append(LINE_FEED);
writer.close();// checks server's status code firstint status = httpConn.getResponseCode();if(status ==HttpURLConnection.HTTP_OK){BufferedReader reader =newBufferedReader(newInputStreamReader(
httpConn.getInputStream()));String line =null;while((line = reader.readLine())!=null){
response.add(line);}
reader.close();
httpConn.disconnect();}else{thrownewIOException("Server returned non-OK status: "+ status);}return response;}}
Use it (Async way)
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
// In your case you are not adding form data so ignore this
/*This is to add parameter values */
for (int i = 0; i < myFormDataArray.size(); i++) {
multipart.addFormField(myFormDataArray.get(i).getParamName(),
myFormDataArray.get(i).getParamValue());
}
//add your file here.
/*This is to add file content*/
for (int i = 0; i < myFileArray.size(); i++) {
multipart.addFilePart(myFileArray.getParamName(),
new File(myFileArray.getFileName()));
}
List<String> response = multipart.finish();
Debug.e(TAG, "SERVER REPLIED:");
for (String line : response) {
Debug.e(TAG, "Upload Files Response:::" + line);
// get your server response here.
responseString = line;
}
Upload (POST) file using HttpURLConnection
Quite often it's necessary to send/upload a file to a remote server, for example, an image, video, audio or a backup of the application database to a remote private server. Assuming the server is expecting a POST request with the content, here's a simple example of how to complete this task in Android.
File uploads are sent using multipart/form-data POST requests. It's very easy to implement:
URL url =newURL(postTarget);HttpURLConnection connection =(HttpURLConnection) url.openConnection();String auth ="Bearer "+ oauthToken;
connection.setRequestProperty("Authorization", basicAuth);String boundary = UUID.randomUUID().toString();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","multipart/form-data;boundary="+ boundary);DataOutputStream request =newDataOutputStream(uc.getOutputStream());
request.writeBytes("--"+ boundary +"\r\n");
request.writeBytes("Content-Disposition: form-data; name=\"description\"\r\n\r\n");
request.writeBytes(fileDescription +"\r\n");
request.writeBytes("--"+ boundary +"\r\n");
request.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""+ file.fileName +"\"\r\n\r\n");
request.write(FileUtils.readFileToByteArray(file));
request.writeBytes("\r\n");
request.writeBytes("--"+ boundary +"--\r\n");
request.flush();int respCode = connection.getResponseCode();switch(respCode){case200://all went ok - read response...break;case301:case302:case307://handle redirect - for example, re-post to the new location...break;...default://do something sensible}
Of course, exceptions will need to be caught or declared as being thrown. A couple points to note about this code:
postTarget is the destination URL of the POST; oauthToken is the authentication token; fileDescription is the description of the file, which is sent as the value of field description; file is the file to be sent - it's of type java.io.File - if you have the file path, you can use new File(filePath) instead.
It sets Authorization header for an oAuth auth
It uses Apache Common FileUtil to read the file into a byte array - if you already have the content of the file in a byte array or in some other way in memory, then there's no need to read it.
A multi-purpose HttpURLConnection class to handle all types of HTTP requests
The following class can be used as a single class that can handle GET, POST, PUT, PATCH, and other requests:
Use any of the given constructors of the class depending on whether you need to send POST data or any extra headers.
The onComplete() method will be called when the data fetching is complete. The data is returned as an object of the APIResponseObject class, which has a status code stating the HTTP status code of the request and a string containing the response. You can parse this response in your class, i.e. XML or JSON.
Call execute() on the object of the class to execute the request, as shown in the following example:
HttpURLConnection(opens new window) is the standard HTTP client for Android, used to send and receive data over the web. It is a concrete implementation of URLConnection for HTTP (RFC 2616).