In this article, I invite the reader to discover the different methods to access http resources from the Android platform.
These methods can be adapted to access web services (using REST) or simply to download files !
Contents
- 1 First Method : getting an input stream given a simple url from Android using HttpURLConnection
- 2 Second Method : getting an input stream given a simple url from Android using HttpClient
- 3 Reading / Sending a cookie along with the requests
- 4 Converting the InputStream into a Drawable in Android
- 5 Converting the InputStream into a String in Android
First Method : getting an input stream given a simple url from Android using HttpURLConnection
This method is the most basic one : it allows you, using the basic HttpUrlConnection, ( contained in java.net) to get an InputStream from an Url :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
private InputStream downloadUrl(String url) { HttpURLConnection con = null; URL url; InputStream is=null; try { url = new URL(url); con = (HttpURLConnection) url.openConnection(); con.setReadTimeout(10000 /* milliseconds */); con.setConnectTimeout(15000 /* milliseconds */); con.setRequestMethod("GET"); con.setDoInput(true); con.addRequestProperty("Referer", "http://blog.dahanne.net"); // Start the query con.connect(); is = con.getInputStream(); }catch (IOException e) { //handle the exception ! e.printStackTrace(); } return is; } |
You can also use the Post method, sending data in the HTTP POST payload :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
private InputStream downloadUrl(String url) { InputStream myInputStream =null; StringBuilder sb = new StringBuilder(); //adding some data to send along with the request to the server sb.append("name=Anthony"); URL url; try { url = new URL(url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); OutputStreamWriter wr = new OutputStreamWriter(conn .getOutputStream()); // this is were we're adding post data to the request wr.write(sb.toString()); wr.flush(); myInputStream = conn.getInputStream(); wr.close(); } catch (Exception e) { //handle the exception ! Log.d(TAG,e.getMessage()); } return myInputStream; } |
But there are better ways to achieve that, using Apache HttpClient, included in android.jar (no need to add another jar, it’s included in android core)
Second Method : getting an input stream given a simple url from Android using HttpClient
Why is it a better to do it ? because the simpler, the better ! See by yourself :
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public static InputStream getInputStreamFromUrl(String url) { InputStream content = null; try { HttpGet httpGet = new HttpGet(url); HttpClient httpclient = new DefaultHttpClient(); // Execute HTTP Get Request HttpResponse response = httpclient.execute(httpGet); content = response.getEntity().getContent(); } catch (Exception e) { //handle the exception ! } return content; } |
But you maybe wondering if it’s still easy with HTTP Post method ? You won’t be deceived !
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public static InputStream getInputStreamFromUrl(String url) { InputStream content = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); List nameValuePairs = new ArrayList(1); //this is where you add your data to the post method nameValuePairs.add(new BasicNameValuePair( "name", "anthony")); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httpPost); content = response.getEntity().getContent(); return content; } } |
But what if you want to read a cookie from the response ? And how can you send a cookie back to the server for the next request ?
Using Apache HttpClient, it’s easy to retrieve cookies ! Everything is in the headers after all !
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
[...] Cookie sessionCookie =null; HttpResponse response = httpclient.execute(httpPost); Header[] allHeaders = response.getAllHeaders(); CookieOrigin origin = new CookieOrigin(host, port,path, false); for (Header header : allHeaders) { List parse = cookieSpecBase.parse(header, origin); for (Cookie cookie : parse) { // THE cookie if (cookie.getName().equals(COOKIE_I_WAS_LOOKING_FOR) && cookie.getValue() != null && cookie.getValue() != "") { sessionCookie = cookie; } } } |
To send a cookie along with your request, keep it simple :
1 2 3 4 5 6 7 |
HttpPost httpPost = new HttpPost(url); CookieSpecBase cookieSpecBase = new BrowserCompatSpec(); List cookies = new ArrayList(); cookies.add(sessionCookie); List cookieHeader = cookieSpecBase.formatCookies(cookies); // Setting the cookie httpPost.setHeader(cookieHeader.get(0)); |
What about the resulting InputStream ? You definitely want to transform it into a String or an Drawable (to set it to an ImageView for example !) don’t you ?
Converting the InputStream into a Drawable in Android
The Drawable class already handles that for you :
1 |
Drawable d = Drawable.createFromStream(myInputStream, "nameOfMyResource"); |
Converting the InputStream into a String in Android
This is some classic java stuff (don’t tell about how easier it is in Ruby.. I know … but hey ! Java SE7 at the rescue with NIO !!! maybe one day in 2010 ! )
1 2 3 4 5 6 7 8 9 10 |
BufferedReader rd = new BufferedReader(new InputStreamReader(myInputStreamToReadIntoAString), 4096); String line; StringBuilder sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); String contentOfMyInputStream = sb.toString() That's it folks ! If you have any other methods to achieve these goals, feel free to share them sending a comment ! |
Great article! Thank you
It’s very good! Thank you
Hi there!
First of all, great post! I only have one question: it is possible to send a xml string in the HTTP POST payload?
Thanks in advance,
Best regards!
yeah sure, for a REST POST action for example !
Hi again!
I´m developing a client application that must send a xml string with the requests to a HTTP server, that is running on port 2323. My approach, is to establish a socket and send a HTTP POST with a xml string. In your examples, you only use the URL to establish the connections but, the server only listens the port 2323 and so I think I must establish a connection through a socket.
Could you give any suggestion?
Thanks in advance,
Best regards!
Hello Rui !
you only have to specify the port at the end of the URL, HttpClient will guess it !
for example :
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(« http://myurl:2323 »);
will do the trick !
Hi Anthony!
Thanks for your help so far. It is necessary any additional network configuration in the Android emulator to send the request to the server?
Best regards!
No ! I suggest you to try, it is the best way to learn !
Hi!
I know trying it’s the best way to learn but the designated time for this project is very short! I’ll keep you informed!
Best regards and thanks for the help,
Rui
Hi again!
It is possible to change this code
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List nameValuePairs = new ArrayList(1);
//this is where you add your data to the post method
nameValuePairs.add(new BasicNameValuePair(
« name », « anthony »));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httpPost);
content = response.getEntity().getContent();
return content;
}
in order to send not pairs of values but a xml string?
Thanks for the help,
Best regards!
Hi All,
I want a peice of code for https communication.
Objective is sending a xml file to the web server with https.
Thanks and Regards,
jit
Has anyone figured out how to send xml as the payload in a POST? Nothing I do seems to work. I thin I need to encode the xml somehow but nothing has worked so far. Any ideas?
hi ,
how can iuse HttpDelete and also post an xml.
Please help.
Thanks
Thanks for the article… It is very useful!
Let say I have a tabview which every tab I have pre-loaded an URL with webview. On the page of webview, I have a link to download a file. How can I implement this to download that file to the phone?
Appreciated it!
Philip
Hello Philip !
To download a file to hte phone (sdcrad) you just have to create a link to that file (http:∕∕host.com∕file.zip for example), in a webview, and when the user will click on the link, android will ask the user where he wants to download it.
Thanks but that is not a solution ;(.
I’ve tried that but it does nothing!(Like if that’s a large video file, .mp4). Link to an image just open an image, not to save. I want to save :). I meant the webview in the app somehow does not handle the requests like in its real browser!
I’m on Droid 2.0.1.
Philip
//I want to save temparary media file to sdcard using following code
File temp = File.createTempFile(« /sdcard/Sipdroid/mediaplayertmp », « dat »);
String tempPath = temp.getAbsolutePath();
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[128];
do {
int numread = fis.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
} while (true);
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(tempPath);
mp.start();
Hey..
Gr8 articles.. helped us a lot
Thank you.
Its very useful for me. how to upload .doc file from android to servlet. like resume attachment from android
Hello there, how can I read de »content », how can I make it back to a String for example? My PHP echo’s a link which I’d like the android to use .. can somebody help me please?
Hi there again, how can we POST an array, instead of the value pair?
Can someone help me with this? To make the « Second Method : getting an input stream given a simple url from Android using HttpClient » able to send also an Array of strings to receive later in PHP instead of being limited to a BasicNamePair ?
Thank you…
Any help is REALLY WELCOME with this :/
Hi, I am having issues as to how i can pars and extract the XML contnet and attachment from an Httpurlconnection. Please help . Sample source code will be great help.
Thanks in advance
This is a great article.
But I have a question.
If HTTP connection was disconnected while receiving the response via InputStream, could I detect this failour?
I tested it on emulator, but no any exception is occurred in this case.
Best Regards.
Ricos.
Brilliant article……Made my life easy…thanks
How about the sending? Can you show how an example of reading an image from the SD Card and then transmitting it via POST?
Hi there,
I have issues sending cookies with an HTTP post. Itried your piece of code but have problems with the setheader part. It returns the method is not applicable with the argument object. Could you help me with that part?
Thanks a lot
Thom
Great article, thanks!
When I try to GET most sites (say http://www.google.com) it works perfectly. But for some reason some sites always return a « 400 Bad Request » error. One site in particular is http://www.pillreports.com
It works fine in my phone’s browser but I can’t GET it in code. Any ideas?
All the best,
Mark
Great article. It solved a very weird trouble I was having with my code. Thank you.
Hi, Your article is nice!
I am working with sending audio files from android to ip camera. I am using an ip camera from axis communications. In their api they are using http://ipadress/axis-cgi/audio/transmit.cgi
the method is post and there are no arguments to this cgi.
Can you help me in this problem, how can i send a file from android to ip camera using the above syntax over http request.
thanks & regards,
sudheer
how to post images data to server in android…or javaaaaaaa
Hi,
Nice artice, however in my case it does not work. It only retreive half data, after that it exist from inputstream loop. It show total 332k, but actually it only retreive around 200k. I don’t understand, why HttpUrlConnection as well as HttpClient does not work properly with Android.
Thank you
Is it possible to use Android’s system cache with the HttpClient? UrlConnection provides the useCaches(true) method (in addition with ResponseCache.getDefault()) for this approach – instead of writing your own cache (e.g. for local caching of images in a ListView or Gallery).
Thanks and regards
Thorsten
hello Thorsten, I was not aware of this useCaches(true) method; it sounds interesting !
Even though, using your own cache can come in handy if you want to store albums and albums of photos for example !
thanks for the tip !
Hi Anthony, good post!
Looking at your 2nd example, the POST example, how can more than one form input be sent to the server?
i’m trying to do webview android but i cant display a webpage name http://gothere.sg/api/maps/overview.html
i always get this problem when i run emulator
e.g the web page at file:///android_asset/gothere.html.could not be loaded as :
the request was not found !!!
internet access
interface
JavaScript all are inside
because i’m doing this for my major project in school
could it be a http dev issue
Hi Anthony,
Android Question:- Could you please help me am struggling web server connection task.My task is that i have a login page i have to integrate it to home page but to verify login page i have to send some data to server end that i json format how can i do please help me if you can provide some code please do it.
Thanks in advance
hello i am mongolia.
Android question:
interface
Nice Tutorial….
Hi Anthony,
Nice tutorial … I am having a problem though … I am usind http post to login to a website. I am sending username and password as key value pairs. But i am getting an empty response. I cant figure out the problem. Can you please help me out?
hi Anthoni.. your post was great.. but i think u miss the answer for several question
i’ll help you to answer some question
@Rui, you can add the XML to the parameter.
i.e
nameValuePairs.add(new BasicNameValuePair(, myXML));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
make sure you convert the XML to a String myXML.. hope this usefull
@Anthoni
can you give me sample code, or explanation about HTTPS with Android??
it seems
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List nameValuePairs = new ArrayList(1);
//this is where you add your data to the post method
nameValuePairs.add(new BasicNameValuePair(
« name », « anthony »));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httpPost);
content = response.getEntity().getContent();
it can only work with HTTP, i dont know how to get it work on HTTPS, for note i’m using GLASSFISH default key for HTTPS (https:localhost/MyWeb:8181)
thx before
hello Tommy,
for HTTPS, you have to play with ssl keystore.
some stuff I did for RegalAndroid, for G2 :
// avoid instanciating
SchemeRegistry schemeRegistry = new SchemeRegistry();
// http scheme
schemeRegistry.register(new Scheme(« http », PlainSocketFactory
.getSocketFactory(), 80));
// https scheme
schemeRegistry.register(new Scheme(« https », new FakeSocketFactory(),
443));
you can have a look at the class there :
https://github.com/anthonydahanne/ReGalAndroid/blob/master/g2-java-client/src/main/java/net/dahanne/gallery/g2/java/client/business/G2Client.java
Thanks for answering some comments
hello Anthony, thanks for you quick reply
i’ve take a look the link that you give to me, it seems that whatever the certificate it will always validate it « true ». is that really safe to do it? is there another ways to validate the certificate? thanks for your help, i really apreciate that
you’re welcome; you’re right, probably not that safe to accept all the certificates; but very convenient… You have to choose your approach : a most complete one, with a GUI to deal with all the certificates; or the quick and dirty one, that allows HTTPS user to have a first working version, in no time. It’s your call !
Hi Anthony,
I am having trouble reading a plain xml file(REST web service).
I have an GET(see code below) Method here(Getting the right result: HTTP status + xml).
However when trying with an POST Method i only get the HTTP status, but the xml file are not displayed at the screen.
Can you help me figure out what am I doing wrong on the POST part.
Notice! I have two service one that requires GET and the other POST
// This is the GET method part
private DefaultHttpClient httpClient = new DefaultHttpClient();
private int responseCode;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv1 = (TextView)findViewById(R.id.text1);
TextView tv3 = (TextView)findViewById(R.id.text3);
try {
HttpGet httpGet = new HttpGet (« http://myURL »);
httpGet.setHeader(« Host », « myhost »);
httpGet.setHeader(« Authorization », « username:password »);
httpGet.setHeader(« Content-Type », »Content-Type: application/xml; charset=utf-8″);
HttpResponse httpResponse = httpClient.execute(httpGet);
responseCode = httpResponse.getStatusLine().getStatusCode();
if(responseCode == 200){
HttpEntity entity = httpResponse.getEntity();
String xml = EntityUtils.toString(entity);
httpResponse = httpClient.execute(httpGet);
httpResponse.getEntity();
tv3.setText(xml.toString());
String reden = httpResponse.getStatusLine().getReasonPhrase();
tv1.setText(« \n\nHTTP Statuscode : » + responseCode+ » « +reden);
}else{
String reden = httpResponse.getStatusLine().getReasonPhrase();
throw new RuntimeException(« Problem reading status (code= »+responseCode + »): »+reden);
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
//Post part
private DefaultHttpClient httpClient = new DefaultHttpClient();
private int responseCode;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv1 = (TextView)findViewById(R.id.text1);
TextView tv2 = (TextView)findViewById(R.id.text2);
TextView tv3 = (TextView)findViewById(R.id.text3);
try {
HttpPost httpPost = new HttpPost(« http://myURL »);
httpPost.addHeader(« Host », »myhost.com »);
httpPost.addHeader(« Authorization », » username:password »);
httpPost.addHeader(« Content-Type », »application/xml; charset=utf-8″);
HttpResponse httpResponse = httpClient.execute(httpPost);
responseCode = httpResponse.getStatusLine().getStatusCode();
if(responseCode == 200){
HttpEntity entity = httpResponse.getEntity();
String xml = EntityUtils.toString(entity);
httpResponse = httpClient.execute(httpPost);
httpResponse.getEntity();
tv3.setText(xml.toString());
String reason = httpResponse.getStatusLine().getReasonPhrase();
tv1.setText(« \n\nHTTP Statuscode : » + responseCode+ » « +reason);
}else{
String reason = httpResponse.getStatusLine().getReasonPhrase();
tv2.setText(« \n\nHTTP Statuscode : » + responseCode+ » « +reason);
throw new RuntimeException(« Problemen bij het lezen van het status (code= »+responseCode + »): »+reason);
}
InputStream in = httpResponse.getEntity().getContent();
//BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
}catch (IOException e){
//
} catch (Exception e1) {
//
}
}}
Thanks in advance
Hi,
This is a very useful article for beginner like me.
Thanks
But sometime i got the IOException when call goes to execute method of HttpGet/HttpPost.
i think this url problem but when i paste same url into web browser it gives me response.
i don’t know why this is done.
Please, can you provide me the appropriate answer?
Thanks in advance.
Hello,
I am new to android development can you show how the request and response works in android using any small example(if 1 text field requesting something and taking response when clicked on to button).
can you help me on this. Webservice is new to me…
@ Upschool : try
response.getEntity().getContent(); (this will return you InputStream to parse)
instead of just
response.getEntity()
I am trying to display a website from within an android app. I basically want to leave my app and bring up a website on the phones default browser. For example, create a button that says NASDAQ in an app and when it is pressed it loads the default phone browser with the http://www.nasdaq.com website in it.
Any help would be greatly appreciated.
Here is my current code.
.setNeutralButton(« Buy stock », new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(« http://www.nasdaq.com/ »);
HttpResponse response = null;
try {
response = httpclient.execute(httpget);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = null;
try {
instream = entity.getContent();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int l;
byte[] tmp = new byte[2048];
try {
while ((l = instream.read(tmp)) != -1) {
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
})
Hi Anthony,
I tryed both methods to get http resources described above, very similar to other examples I found on the web, but I can’t manage them to work.
I always get the following exception:
INFO/System.out(278): Excpetion = java.net.UnknownHostException: oxavi.com
It seems it’s the same problem described by Bipin Vayalu but I can’t see any reply on this.
I added to my AndroidManifest file the user permission:
android:name= »android.permission.INTERNET »
but it didn’t solve the problem.
I tryed both on my HW(HTC WildFire android 2.2.1) and on the AVDs with no results.
Do I miss some important configuration for the internet access ?
Do you think it is possible to handle the http connection directly into the event handler or I need to create a separate thread ?
=============== This is the code =====================
final Button buttonSearch = (Button) findViewById(R.id.search);
buttonSearch.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == android.view.MotionEvent.ACTION_DOWN){
try {
System.out.println(« \n\n BUTTON PUSHED\n\n »);
InputStream content = null;
HttpGet httpGet = new HttpGet(« http://oxavi.com/price.php »);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
BufferedReader rd = new BufferedReader(new InputStreamReader(content), 4096);
String line;
StringBuilder sb = new StringBuilder();
while ((line = rd.readLine()) != null)
{ sb.append(line);}
rd.close();
String contentOfMyInputStream = sb.toString();
System.out.println(contentOfMyInputStream);
} catch (Exception e){
System.out.println(« Excpetion = » + e);}
}
return true;
}
});
===================================================
Many thanks in advance.
Andrea
Reading / Sending a cookie along with the requests.can you provide entire code for this i was struggle with this lot. please.
Hi Anthony,
You may find this somehow unrelated to your efforts towards accessing http resources from Android but I will appreciate it if you can provide me with your thoughts regarding to my challenge.
I’m trying to capture some statistics like number of 302’s and 200 Oks or the time it takes for the client to receive the content from the streamer (time it takes from the actual request (URL) to the http client till http client sends the content back to the media player). The cleanest way to do this is to extend HttpClient code. The challenge for me is to know that if the media player (any kind) on Android will use my extended version of HttpClient or not. I will appreciate it if you can help me at least based on your experience what you think about this.
Cheers, STZ
Maybe you could use convertStreamToString to convert the InputStream into a string:
JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));
ByteArrayOutputStream stream_bytes=new ByteArrayOutputStream();
int cnt=0;
byte[] buffer=new byte[512];
while ((cnt=stream_content.read(buffer))!=-1)
{stream_bytes.write(buffer, 0, cnt);
}
String response_text=new String(stream_bytes.toByteArray());
or
BufferedReader br=new BufferedReader(new InputStreamReader(stream_content), 4096);
String line;
StringBuilder sb=new StringBuilder();
while ((line=br.readLine())!=null)
{sb.append(line);
}
String contentOfMyInputStream=sb.toString();
hi Andrea
i have faced such problem of unknown host .
check your internet connection ..
or if you are testing with emulator so set dns server for emulator like
start cmd
change directory to android-sdk/tools
and
fire this command
emulator.exe -avd [your avd name] -dns-server 192.168.1.1
thats it.
run your app…
hope this will help you
I think the best way how to get String content from InputStrem is:
Note: Don’t forget on right charset, see second parameter in InputStreamReader constructor.
really its awesome code
This did not work.
package mainpackage.rest_client;
import mainpackage.rest_client.R;
import mainpackage.rest_client.util.*;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.util.Patterns;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends Activity {
protected static final boolean TOGGLE_ON_CLICK = false;
private SystemUiHider mSystemUiHider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final View contentView = findViewById(R.id.methlayout);
contentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
ImageButton button = (ImageButton) findViewById(R.id.btn_send);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
urlvalidate(v);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
/* case R.id.menu_file:
// Single menu item is selected do something
// Ex: launching new activity/screen or show alert message
Toast.makeText(AndroidMenusActivity.this, « Bookmark is Selected », Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_authentication:
Toast.makeText(AndroidMenusActivity.this, « Save is Selected », Toast.LENGTH_SHORT).show();
return true;*/
case R.id.menu_request:
startActivity(new Intent(this, MainActivity.class));
return true;
case R.id.menu_response:
startActivity(new Intent(this, ResponseActivity.class));
return true;
/* case R.id.menu_header:
Toast.makeText(AndroidMenusActivity.this, « Delete is Selected », Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_setting:
Toast.makeText(AndroidMenusActivity.this, « Preferences is Selected », Toast.LENGTH_SHORT).show();
return true;*/
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
// delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
//View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
//@Override
/* public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}*/
//};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
@Override
public void run() {
mSystemUiHider.hide();
}
};
public void urlvalidate(View view){
EditText textField = (EditText) findViewById(R.id.email_address);
String enteredUrl = textField.getText().toString();
if (Patterns.WEB_URL.matcher(enteredUrl).matches()) {
startActivity(new Intent(this, ResponseExpandableListActivity.class));
}
else {
Toast.makeText(this, « URL is invalid! », Toast.LENGTH_SHORT).show();
textField.setText(« »);
}};
}
The code is for https post with a cookie. In line 8 of this code, I am not able to get the cookieHeader from the List. I tried few magic but failed to get it to work.
Many thx
public static InputStream getInputStreamFromUrl(String url) {
InputStream content = null;
try {
HttpPost httpPost = new HttpPost(url);
CookieSpecBase cookieSpecBase = new BrowserCompatSpec();
List cookies = new ArrayList();
cookies.add(cookieSpecBase);
List cookieHeader = cookieSpecBase.formatCookies(cookies);
// Setting the cookie
httpPost.setHeader(« Cookie », cookieHeader.get(0).toString());
HttpClient httpclient = new DefaultHttpClient();
httpPost = new HttpPost(url);
List nameValuePairs = new ArrayList(1);
nameValuePairs.add(new BasicNameValuePair(« userName », « a »));
nameValuePairs.add(new BasicNameValuePair(« password », « b »));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httpPost);
content = response.getEntity().getContent();
return content;
} catch (Throwable e) {
}
return null;
}