Friday, December 10, 2010

Android GET, POST and Multipart POST and downloader simple

HttpGet simple

try {
        HttpClient client = new DefaultHttpClient(); 
        String getURL = "http://www.google.com";
        HttpGet get = new HttpGet(getURL);
        HttpResponse responseGet = client.execute(get); 
        HttpEntity resEntityGet = responseGet.getEntity(); 
        if (resEntityGet != null) { 
                    //do something with the response
                    Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
                }
} catch (Exception e) {
    e.printStackTrace();
}

HttpPost simple


try {
        HttpClient client = new DefaultHttpClient(); 
        String postURL = "http://somepostaddress.com";
        HttpPost post = new HttpPost(postURL);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("user", "kris"));
            params.add(new BasicNameValuePair("pass", "xyz"));
            UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
            post.setEntity(ent);
            HttpResponse responsePOST = client.execute(post); 
            HttpEntity resEntity = responsePOST.getEntity(); 
            if (resEntity != null) {   
                Log.i("RESPONSE",EntityUtils.toString(resEntity));
            }
    } catch (Exception e) {
        e.printStackTrace();
    }

MultipartEntity

File file = new File("path/to/your/file.txt");
try {
         HttpClient client = new DefaultHttpClient(); 
         String postURL = "http://someposturl.com";
         HttpPost post = new HttpPost(postURL);
     FileBody bin = new FileBody(file);
     MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
     reqEntity.addPart("myFile", bin);
     post.setEntity(reqEntity); 
     HttpResponse response = client.execute(post); 
     HttpEntity resEntity = response.getEntity(); 
     if (resEntity != null) {   
               Log.i("RESPONSE",EntityUtils.toString(resEntity));
         }
} catch (Exception e) {
    e.printStackTrace();
}





Image or Text downloader good and full simple



import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: boroo
 * Date: Dec 9, 2010
 * Time: 6:01:41 PM
 * To change this template use File | Settings | File Templates.
 */
public class WebUtils {

    public WebUtils() {
    }

    private InputStream OpenHttpConnection(String urlString)
            throws IOException {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");

        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();

            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        }
        catch (Exception ex) {
            throw new IOException("Error connecting");
        }
        return in;
    }

    public String DownloadText(String URL) {
        int BUFFER_SIZE = 2000;
        InputStream in = null;

        try {
            in = OpenHttpConnection(URL);
        } catch (IOException e1) {
            e1.printStackTrace();
            return "";
        }

        InputStreamReader isr = new InputStreamReader(in);
        int charRead;
        StringBuilder str = new StringBuilder();
        char[] inputBuffer = new char[BUFFER_SIZE];

        try {
            while ((charRead = isr.read(inputBuffer)) > 0) {
                //---convert the chars to a String---
                String readString =
                        String.copyValueOf(inputBuffer, 0, charRead);
                str.append(readString);
                inputBuffer = new char[BUFFER_SIZE];
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        return str.toString();
    }

    public Document DownloadXML(String URL) {
        try {
            InputStream in = OpenHttpConnection(URL);
            Document doc = null;
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db;

            try {
                db = dbf.newDocumentBuilder();
                doc = db.parse(in);
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            }
            return doc;
        } catch (Exception e1) {
            e1.printStackTrace();
            return null;
        }
    }

    public Bitmap DownloadImage(String URL) {
        Bitmap bitmap = null;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return bitmap;
    }


    ///////////////////////// static methods ////////////////////

    public static final String buildUri(String uri, Map<String, String> map)
            throws IllegalArgumentException {
        StringBuilder sb = new StringBuilder();
        sb.append(uri);
        int i = 0;

        if (map != null && !map.isEmpty()) {

            for (String key : map.keySet()) {
                if (i == 0) {
                    sb.append("?");
                } else {
                    sb.append("&");
                }

                sb.append(key);
                sb.append("=");
                sb.append(map.get(key));

                i++;
            }
        }
        return sb.toString();
    }
}

No comments: