Different ways to access HTTP resources from Android

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 !

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 :

You can also use the Post method, sending data in the HTTP POST payload :

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 :

But you maybe wondering if it’s still easy with HTTP Post method ? You won’t be deceived !

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 ?

Reading / Sending a cookie along with the requests

Using Apache HttpClient, it’s easy to retrieve cookies ! Everything is in the headers after all !

To send a cookie along with your request, keep it simple :

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 :

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 ! )

62 réflexions sur « Different ways to access HTTP resources from Android »

  1. 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!

  2. 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!

  3. 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 !

  4. 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!

  5. 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

  6. 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!

  7. 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

  8. 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?

  9. 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

  10. 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.

  11. 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

  12. //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();

  13. Its very useful for me. how to upload .doc file from android to servlet. like resume attachment from android

  14. 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?

  15. 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 :/

  16. 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

  17. 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.

  18. How about the sending? Can you show how an example of reading an image from the SD Card and then transmitting it via POST?

  19. 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

  20. 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

  21. 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

  22. 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

  23. 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 !

  24. Hi Anthony, good post!

    Looking at your 2nd example, the POST example, how can more than one form input be sent to the server?

  25. 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

  26. 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

  27. 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?

  28. 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

  29. 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 ;-)

  30. 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

  31. 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 !

  32. 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

  33. 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.

  34. 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…

  35. @ Upschool : try

    response.getEntity().getContent(); (this will return you InputStream to parse)

    instead of just

    response.getEntity()

  36. 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();
    }
    }

    }
    })

  37. 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

  38. Reading / Sending a cookie along with the requests.can you provide entire code for this i was struggle with this lot. please.

  39. 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

  40. Maybe you could use convertStreamToString to convert the InputStream into a string:


    JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));


  41. 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();

  42. 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

  43. I think the best way how to get String content from InputStrem is:

    BufferedReader br=new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    
    StringBuilder sb=new StringBuilder();
    
    char[] buffer = new char[8192];
    int len;
    
    while ((len = br.read(buffer)!= -1) {
      sb.append(buffer, 0, len);
    }
    
    String content = sb.toString();
    

    Note: Don’t forget on right charset, see second parameter in InputStreamReader constructor.

  44. 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(«  »);
    }};

    }

  45. 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;
    }

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *