Http Request Class : Http Connection « Network « Android






Http Request Class

    
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import android.util.Log;

class HttpData {
  public String content;
  public Hashtable cookies = new Hashtable();
  public Hashtable headers = new Hashtable();
}

public class HttpRequest {

  /**
   * HttpGet request
   * 
   * @param sUrl
   * @return
   */
  public static HttpData get(String sUrl) throws Exception {
    HttpData ret = null;
    String str;
    StringBuffer buff = new StringBuffer();
    // try {
    URL url = new URL(sUrl);
    URLConnection con = url.openConnection();

    BufferedReader in = new BufferedReader(new

    InputStreamReader(con.getInputStream()));
    // boolean notRemoveNewLine = sUrl.contains("news");
    // if (notRemoveNewLine) {
    // while ((str = in.readLine()) != null) {
    // buff.append(str + Global.NEW_LINE_CHAR);
    // }
    // } else {
    // while ((str = in.readLine()) != null) {
    // buff.append(str);
    // }
    // }
    while ((str = in.readLine()) != null) {
      buff.append(str);
    }

    ret = new HttpData();
    ret.content = buff.toString();
    // get headers
    Map<String, List<String>> headers = con.getHeaderFields();
    Set<Entry<String, List<String>>> hKeys = headers.entrySet();
    for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i
        .hasNext();) {
      Entry<String, List<String>> m = i.next();

      ret.headers.put(m.getKey(), m.getValue().toString());
      if (m.getKey().equals("set-cookie"))
        ret.cookies.put(m.getKey(), m.getValue().toString());
    }
    // } catch (Exception e) {
    // e.printStackTrace();
    // Log.e("HttpRequest", e.toString());
    // }
    return ret;
  }

  /**
   * HTTP post request
   * 
   * @param sUrl
   * @param ht
   * @return
   * @throws Exception
   */
  public static HttpData post(String sUrl, Hashtable<String, String> ht)
      throws Exception {
    String key;
    StringBuffer data = new StringBuffer();
    Enumeration<String> keys = ht.keys();
    while (keys.hasMoreElements()) {
      key = keys.nextElement();
      data.append(URLEncoder.encode(key, "UTF-8"));
      data.append("=");
      data.append(URLEncoder.encode(ht.get(key), "UTF-8"));
      data.append("&amp;");
    }
    return HttpRequest.post(sUrl, data.toString());
  }

  /**
   * HTTP post request
   * 
   * @param sUrl
   * @param data
   * @return
   */
  public static HttpData post(String sUrl, String data) {
    StringBuffer ret = new StringBuffer();
    HttpData dat = new HttpData();
    String header;
    try {
      // Send data
      URL url = new URL(sUrl);
      URLConnection conn = url.openConnection();
      conn.setDoOutput(true);
      OutputStreamWriter wr = new OutputStreamWriter(
          conn.getOutputStream());
      wr.write(data);
      wr.flush();

      // Get the response

      Map<String, List<String>> headers = conn.getHeaderFields();
      Set<Entry<String, List<String>>> hKeys = headers.entrySet();
      for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i
          .hasNext();) {
        Entry<String, List<String>> m = i.next();

        dat.headers.put(m.getKey(), m.getValue().toString());
        if (m.getKey().equals("set-cookie"))
          dat.cookies.put(m.getKey(), m.getValue().toString());
      }
      BufferedReader rd = new BufferedReader(new

      InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = rd.readLine()) != null) {
        ret.append(line);
      }
      Log.e("ERROR", line);
      wr.close();
      rd.close();
    } catch (Exception e) {
      e.printStackTrace();
      Log.e("ERROR", "ERROR IN CODE:" + e.getMessage());
    }
    dat.content = ret.toString();
    return dat;
  }
  /**
   * Post request (upload files)
   * 
   * @param sUrl
   * @param files
   * @return HttpData
   */
  /*
   * public static HttpData post(String sUrl, ArrayList<File> files) {
   * Hashtable<String, String> ht = new Hashtable<String, String>(); return
   * HttpRequest.post(sUrl, ht, files); }
   */
  /**
   * Post request (upload files)
   * 
   * @param sUrl
   * @param params
   *            Form data
   * @param files
   * @return
   */
  /*
   * public static HttpData post(String sUrl, Hashtable<String, String>
   * params, ArrayList<File>
   * 
   * files) { HttpData ret = new HttpData(); try { String boundary =
   * "*****************************************"; String newLine = "rn"; int
   * bytesAvailable; int bufferSize; int maxBufferSize = 4096; int bytesRead;
   * 
   * URL url = new URL(sUrl); HttpURLConnection con = (HttpURLConnection)
   * url.openConnection(); con.setDoInput(true); con.setDoOutput(true);
   * con.setUseCaches(false); con.setRequestMethod("POST");
   * con.setRequestProperty("Connection", "Keep-Alive");
   * con.setRequestProperty("Content-Type",
   * 
   * "multipart/form-data;boundary="+boundary); DataOutputStream dos = new
   * DataOutputStream(con.getOutputStream());
   * 
   * //dos.writeChars(params);
   * 
   * //upload files for (int i=0; i<files.size(); i++) { Log.i("HREQ", i+"");
   * FileInputStream fis = new FileInputStream(files.get(i));
   * dos.writeBytes("--" + boundary + newLine);
   * dos.writeBytes("Content-Disposition: form-data; " +
   * "name="file_"+i+"";filename="" + files.get(i).getPath() +""" + newLine +
   * newLine); bytesAvailable = fis.available(); bufferSize =
   * Math.min(bytesAvailable, maxBufferSize); byte[] buffer = new
   * byte[bufferSize]; bytesRead = fis.read(buffer, 0, bufferSize); while
   * (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable =
   * fis.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize);
   * bytesRead = fis.read(buffer, 0, bufferSize); } dos.writeBytes(newLine);
   * dos.writeBytes("--" + boundary + "--" + newLine); fis.close(); } // Now
   * write the data
   * 
   * Enumeration keys = params.keys(); String key, val; while
   * (keys.hasMoreElements()) { key = keys.nextElement().toString(); val =
   * params.get(key); dos.writeBytes("--" + boundary + newLine);
   * dos.writeBytes("Content-Disposition: form-data;name="" + key+""" +
   * newLine + newLine + val); dos.writeBytes(newLine); dos.writeBytes("--" +
   * boundary + "--" + newLine);
   * 
   * } dos.flush();
   * 
   * BufferedReader rd = new BufferedReader( new
   * InputStreamReader(con.getInputStream())); String line; while ((line =
   * rd.readLine()) != null) { ret.content += line + "rn"; } //get headers
   * Map<String, List<String>> headers = con.getHeaderFields();
   * Set<Entry<String, List<String>>> hKeys = headers.entrySet(); for
   * (Iterator<Entry<String, List<String>>> i = hKeys.iterator();
   * i.hasNext();) { Entry<String, List<String>> m = i.next();
   * 
   * Log.w("HEADER_KEY", m.getKey() + ""); ret.headers.put(m.getKey(),
   * m.getValue().toString()); if (m.getKey().equals("set-cookie"))
   * ret.cookies.put(m.getKey(), m.getValue().toString()); } dos.close();
   * rd.close(); } catch (MalformedURLException me) {
   * 
   * } catch (IOException ie) {
   * 
   * } catch (Exception e) { Log.e("HREQ", "Exception: "+e.toString()); }
   * return ret; }
   */
}

   
    
    
    
  








Related examples in the same category

1.Http Connection
2.Using HttpGet to get the web response
3.Create Http connection
4.Http connection with
5.HttpGet and DefaultHttpClient
6.Http Post
7.Simple HTTP Request
8.Http Get and Http Post
9.Get Text from HttpResponse
10.Http Request
11.Http Downloader
12.Is Http Url Available
13.Http Retriever
14.Receive Response from HttpURLConnection
15.Print http headers. Useful for debugging.
16.Return the base URL from the given URL. Example: http://foo.org/abc.html -> http://foo.org/
17.Send message with HttpPost
18.Get Http Stream
19.Generic Object Http Loader
20.Http Get and DefaultHttpClient
21.Gets http output from URL
22.Util for Http Get
23.do Http Get Request and return the status code
24.Http Get
25.implements HttpClient
26.Get File From HTTP
27.Make all redirects to go to http in stead of https
28.New Http Client Manager
29.Http Client Manager
30.Multipart Post
31.Get Server Data
32.Yahoo News Crawler
33.Send Packet
34.Read a web page
35.parse Request Header
36.Data Send Utils
37.This class is in charge of synchronizing the events (with due dates) with Google Calendar
38.Update Favicon
39.Converts key-value pair to appropriate signature for Facebook.