10 Jan 2012

This example explains how http request is built with basic authentication in Android.


"border: 1px dashed rgb(153, 153, 153); padding: 5px; overflow: auto; font-family: Andale Mono,Lucida Console,Monaco,fixed,monospace; color: rgb(0, 0, 0); background-color: rgb(238, 238, 238); font-size: 12px; line-height: 14px; width: 100%;">
package test.uitestproject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class UITestProjectActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        TextView returnedText;
        returnedText = (TextView)findViewById(R.id.returnedPage);
        BufferedReader in = null;
        try {
           DefaultHttpClient client = new DefaultHttpClient();
           client.getCredentialsProvider().setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(username,password));
           HttpGet request = new HttpGet();
           request.addHeader("Accept", "application/xml");
           request.setURI(new URI("http://www.assembla.com/spaces/my_spaces"));
           HttpResponse response = client.execute(request);
           in = new BufferedReader
           (new InputStreamReader(response.getEntity().getContent()));
           StringBuffer sb = new StringBuffer("");
           String line = "";
           String NL = System.getProperty("line.separator");
           while ((line = in.readLine()) != null) {
               sb.append(line + NL);
           }
           in.close();
           String page = sb.toString();
           System.out.println(page);
           
           returnedText.setText(page);
        } catch (Exception e) {
        e.printStackTrace();
        returnedText.setText(e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                    } catch (IOException e) {
                    e.printStackTrace();
                    returnedText.setText(e.getMessage());
                }
            }
        }
    }
}

0 comments:

Post a Comment