Android HttpURLConnection Example
Android HttpURLConnection Example
Android
Appium
Python
PostgreSQL
Java Core
Java EE
JDBC
Maven
Spring Core
Angular JS
jQuery
Node JS
Log4j
Selenium
TestNG
Interview Questions
All Tutorials
Contact Me
Search
This article will tell you how to use java.net.HttpURLConnection class to send http request and get
http server response in android application.
https://www.dev2qa.com/android-httpurlconnection-example/ 1/11
27/09/2019 Android HttpURLConnection Example
3. Set request method. The request method can be GET, POST, DELETE etc. Request method must be
uppercase, otherwise below exception will be thrown. java.net.ProtocolException: Expected
one of [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, PATCH] but was get
httpConn.setRequestMethod("GET");
4. If request method is GET, then use below code to open input stream and read server response
data.
InputStream inputStream = httpConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
5. For POST request method, use below code to open output stream to the server url and write post
data to it. After post, open the input stream again to get server response.
OutputStream outputStream = httpConn.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedWriter.write("user=jerry&pasword=666666");
6. After use HttpURLConnection, do not forget close related reader or writer and call
HttpURLConnection’s disconnect() method to close the connection to release network resources.
httpConn.disconnect();
2. HttpURLConnection Examples.
In this example, read server response process is occurred in a child thread. The child thread send a
message to activity main thread’s Handler object to update the response data in TextView.
https://www.dev2qa.com/android-httpurlconnection-example/ 2/11
27/09/2019 Android HttpURLConnection Example
This is because child thread can not update UI controls in activity directly, otherwise an error will
happen.
HttpURLConnectionActivity.java
package com.dev2qa.example.network;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.dev2qa.example.R;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpURLConnectionActivity extends AppCompatActivity {
// Debug log tag.
private static final String TAG_HTTP_URL_CONNECTION = "HTTP_URL_CONNECTION";
// Child thread sent message type value to activity main thread Handler.
private static final int REQUEST_CODE_SHOW_RESPONSE_TEXT = 1;
// The key of message stored server returned data.
private static final String KEY_RESPONSE_TEXT = "KEY_RESPONSE_TEXT";
// Request method GET. The value must be uppercase.
private static final String REQUEST_METHOD_GET = "GET";
https://www.dev2qa.com/android-httpurlconnection-example/ 3/11
27/09/2019 Android HttpURLConnection Example
// Request web page url input text box.
private EditText requestUrlEditor = null;
// Send http request button.
private Button requestUrlButton = null;
// TextView to display server returned page html text.
private TextView responseTextView = null;
// This handler used to listen to child thread show return page html text message and display those text in responseTextVi
private Handler uiUpdater = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_url_connection);
setTitle("dev2qa.com - HttpURLConnection Example");
// Init app ui controls.
initControls();
// When click request url button.
requestUrlButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String reqUrl = requestUrlEditor.getText().toString();
if(!TextUtils.isEmpty(reqUrl))
{
if(URLUtil.isHttpUrl(reqUrl) || URLUtil.isHttpsUrl(reqUrl))
{
startSendHttpRequestThread(reqUrl);
}else
{
Toast.makeText(getApplicationContext(), "The request url is not a valid http or https url.", Toast.LEN
}
}else
{
Toast.makeText(getApplicationContext(), "The request url can not be empty.", Toast.LENGTH_LONG).show();
}
}
});
}
// Initialize app controls.
private void initControls()
{
if(requestUrlEditor == null)
{
requestUrlEditor = (EditText)findViewById(R.id.http_url_editor);
}
if(requestUrlButton == null)
{
requestUrlButton = (Button)findViewById(R.id.http_url_request_button);
}
if(responseTextView == null)
{
responseTextView = (TextView)findViewById(R.id.http_url_response_text_view);
}
// This handler is used to wait for child thread message to update server response text in TextView.
if(uiUpdater == null)
{
uiUpdater = new Handler()
{
@Override
public void handleMessage(Message msg) {
if(msg.what == REQUEST_CODE_SHOW_RESPONSE_TEXT)
{
Bundle bundle = msg.getData();
if(bundle != null)
{
String responseText = bundle.getString(KEY_RESPONSE_TEXT);
responseTextView.setText(responseText);
}
}
}
};
}
}
/* Start a thread to send http request to web server use HttpURLConnection object. */
private void startSendHttpRequestThread(final String reqUrl)
{
Thread sendHttpRequestThread = new Thread()
{
@Override
public void run() {
// Maintain http url connection.
HttpURLConnection httpConn = null;
// Read text input stream.
InputStreamReader isReader = null;
// Read text into buffer.
BufferedReader bufReader = null;
// Save server response text.
StringBuffer readTextBuf = new StringBuffer();
try {
// Create a URL object use page url.
URL url = new URL(reqUrl);
// Open http connection to web server.
httpConn = (HttpURLConnection)url.openConnection();
// Set http request method to get.
httpConn.setRequestMethod(REQUEST_METHOD_GET);
// Set connection timeout and read timeout value.
httpConn.setConnectTimeout(10000);
httpConn.setReadTimeout(10000);
https://www.dev2qa.com/android-httpurlconnection-example/ 4/11
27/09/2019 Android HttpURLConnection Example
// Get input stream from web url connection.
InputStream inputStream = httpConn.getInputStream();
// Create input stream reader based on url connection input stream.
isReader = new InputStreamReader(inputStream);
// Create buffered reader.
bufReader = new BufferedReader(isReader);
// Read line of text from server response.
String line = bufReader.readLine();
// Loop while return line is not null.
while(line != null)
{
// Append the text to string buffer.
readTextBuf.append(line);
// Continue to read text line.
line = bufReader.readLine();
}
// Send message to main thread to update response text in TextView after read all.
Message message = new Message();
// Set message type.
message.what = REQUEST_CODE_SHOW_RESPONSE_TEXT;
// Create a bundle object.
Bundle bundle = new Bundle();
// Put response text in the bundle with the special key.
bundle.putString(KEY_RESPONSE_TEXT, readTextBuf.toString());
// Set bundle data in message.
message.setData(bundle);
// Send message to main thread Handler to process.
uiUpdater.sendMessage(message);
}catch(MalformedURLException ex)
{
Log.e(TAG_HTTP_URL_CONNECTION, ex.getMessage(), ex);
}catch(IOException ex)
{
Log.e(TAG_HTTP_URL_CONNECTION, ex.getMessage(), ex);
}finally {
try {
if (bufReader != null) {
bufReader.close();
bufReader = null;
}
if (isReader != null) {
isReader.close();
isReader = null;
}
if (httpConn != null) {
httpConn.disconnect();
httpConn = null;
}
}catch (IOException ex)
{
Log.e(TAG_HTTP_URL_CONNECTION, ex.getMessage(), ex);
}
}
}
};
// Start the child thread to request web page.
sendHttpRequestThread.start();
}
}
activity_http_url_connection.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/http_url_editor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Input a web page url to get."
android:layout_weight="1"/>
<Button
android:id="@+id/http_url_request_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Request Page"/>
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/http_url_response_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
https://www.dev2qa.com/android-httpurlconnection-example/ 5/11
27/09/2019 Android HttpURLConnection Example
</LinearLayout>
Because this example will connect network resources, so you need to declare below permission in
android manifest xml file.
AndroidManifest.xml
8 COMMENTS
Ghazni Ali
1 year ago Permalink
You made my day Jerry i was stuck on this for the whole day :p i really don’t know what was the
error but your code just worked for me! Great.
Reply
https://www.dev2qa.com/android-httpurlconnection-example/ 6/11
27/09/2019 Android HttpURLConnection Example
pn Hoa
1 year ago Permalink
Reply
enggii
11 months ago Permalink
Hi. I’m working on a android app that will display the position of the baby inside a crib using a
beam sensors connected to RPI3.
I created a webserver on RPI3 that displays the position of the baby. I just want to know how I
can get the web running on my application to see the position of the baby. Thank you
Reply
tom
10 months ago Permalink
Nice !
I have followed many examples without luck
You made my day
But, would you like to show me how to track whether success or failure ?
In my case I need to know the status
Reply
tom
10 months ago Permalink
Solved
Reply
Jerry Zhao
10 months ago Permalink
Reply
Amit Kumar
7 months ago Permalink
https://www.dev2qa.com/android-httpurlconnection-example/ 7/11
27/09/2019 Android HttpURLConnection Example
Reply
Donzaala
5 months ago Permalink
Hi, this article is useful in 2019 lol. How do I only return a server response status. Thank you
Reply
LEAVE A REPLY
Your email address will not be published. Required fields are marked *
Comment
Name *
Email *
Website
https://www.dev2qa.com/android-httpurlconnection-example/ 8/11
27/09/2019 Android HttpURLConnection Example
Post Comment
This site uses Akismet to reduce spam. Learn how your comment data is processed.
report this ad
Search …
RECENT POSTS
report this ad
POPULAR POSTS
https://www.dev2qa.com/android-httpurlconnection-example/ 9/11
27/09/2019 Android HttpURLConnection Example
Passing Data Between Activities Android Tutorial
report this ad
TUTORIAL CATEGORIES
Android Tutorial
Angular JS Tutorial
Appium Tutorial
iOS Tutorial
J2EE Tutorial
Java Tutorial
JDBC Tutorial
JQuery Tutorial
Linux Tutorial
Log4j Tutorial
Mac Tutorial
Maven Tutorial
Network Tutorial
Node JS Tutorial
Python Tutorial
Selenium Tutorial
Spring Boot Tutorial
Spring Tutorial
Test Automation Tutorial
TestNG Tutorial
Tomcat Tutorial
Version Control
Webdriver Tutorial
Windows Tutorial
WordPress Tutorial
TAGS CLOUD
https://www.dev2qa.com/android-httpurlconnection-example/ 10/11
27/09/2019 Android HttpURLConnection Example
Activity Android ActionBar Android Broadcast Android Button Android Content Provider Android Error Android File Android Gesture
Android Image Android Layout Android ListView Android Selector Android Service Android Storage Android Studio Android UI
Best Practice CSV Eclipse Error File Fragment Grid Hello World Http Header IO JAVA BASIC JDBC jQuery Selector Json Logging MySQL PostgreSQL
Python Django RecyclerView Selenium Servlet Spring Spring Bean String Swift Swift Button Tomcat Xcode
XPATH
report this ad
report this ad
https://www.dev2qa.com/android-httpurlconnection-example/ 11/11