Sunday, June 16, 2013

HTTP Requests in Android

This code executes a HTTP POST request with org.apache.http.client.HttpClient. Could be used in combination with "Non-Blocking Web Requests".

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "Cool"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block

Reading response:

Setting up the Android Emulator for HTTP debugging using Fiddler2

Launch an emulator with parameters:

emulator -avd my_avd -http-proxy

Finding proxy:

DefaultHttpClient httpclient = new DefaultHttpClient();

String proxyString = Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.HTTP_PROXY);

if (proxyString != null)
    String proxyAddress = proxyString.split(":")[0];
    int proxyPort = Integer.parseInt(proxyString.split(":")[1]);
    HttpHost proxy = new HttpHost(proxyAddress, proxyPort);

    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

Powered by Blogger.