Home | Русский

How to Send an HTTP POST and GET Requests

As you might imagine, sending an HTTP POST request is a very similar process to sending a GET request.

See example.


public void httpRequest(){
    Connect.getInstance().setParam("all", "getall"));
    Connect.getInstance().setParam("sessionid", "64654sdf465sadf4");
    Connect.getInstance().doPost("http://freesrc.com/");
    while (Connect.getInstance().isActive()) {
        Thread.sleep(20);
    }
    String result = Connect.getInstance().getResult();
}
[/]

[ lang="java"] package freesrc.com; import javax.microedition.io.HttpConnection; import javax.microedition.io.Connector; import java.io.*; import java.util.Enumeration; import java.util.Hashtable; public class Connect extends Thread { /** *reading data */ private byte result[] = null; /** * URL of Server */ private String url = ""; /** * status on connection * true - read data from server * false - finish read data. */ private boolean active = true; private StringBuffer errors = new StringBuffer(0); private static Connect instance = null; public static final int GET = 0; public static final int POST = 1; private Hashtable params = new Hashtable(0); private int method = GET; private Connect() { } public static Connect getInstance() { if (instance == null) { instance = new Connect(); } return instance; } /** * start connection to Server * @param url URL for connection */ public synchronized void doGet(String url) { clearRequest(); this.url = url; method = GET; new Thread(this).start(); } public synchronized void doPost(String url) { clearRequest(); this.url = url; method = POST; new Thread(this).start(); } private void clearRequest() { setActive(true); result = null; errors.setLength(0); } private String prepareRequest() { StringBuffer res = new StringBuffer(); if (params.size() > 0) { int ind = 0; for (Enumeration e = params.keys(); e.hasMoreElements();) { String key = (String) e.nextElement(); if (ind > 0) { res.append("&"); } res.append(key); res.append("="); res.append((String) params.get(key)); ind++; } } return res.toString(); } public void run() { setActive(true); try { if (method == GET) { get(); } else { post(); } } catch (Exception ex1) { ex1.printStackTrace(); } synchronized (this) { setActive(false); } params.clear(); } /** * Connecting to Server * Errors: *
    *
  • #1.01 - Open HTTP Connection
  • *
  • #1.02 - Conection getResponseCode
  • *
  • #1.03 - Connection OpenInputSream
  • *
  • #1.04 - Error Read Data
  • *
  • #1.05 - Error Close InputSream
  • *
  • #1.06 - Error Flush ByteArrayOutputStream
  • *
  • #1.07 - Error Close ByteArrayOutputStream
  • *
  • #1.08 - Response Code Not 200(HttpConnection.HTTP_OK)
  • *
  • #1.09 - Connection is Null
  • *
  • #1.10 - Another Error
  • *
  • #1.11 - Error Close Connection
  • *
      */ private void get() throws Exception { HttpConnection con = null; InputStream is = null; ByteArrayOutputStream but = null; try { try { con = (HttpConnection) Connector.open(url); } catch (IOException w) { throw new Exception("#01\n" + w.getMessage()); } if (con != null) { int response = 0; try { response = con.getResponseCode(); } catch (IOException ex) { throw new Exception("#02\n" + ex.getMessage()); } if (response == HttpConnection.HTTP_OK) { try { is = con.openInputStream(); } catch (IOException ex) { throw new Exception("#03\nCan't OpenInputStream"); } but = new ByteArrayOutputStream(); try { //===Read response=== int ch = 0; ch = is.read(); while (ch != -1) { //System.out.println(ch); but.write(ch); ch = is.read(); } } catch (Exception e) { throw new Exception("#04\nRead Error"); } try { but.flush(); } catch (Exception e) { //throw new Exception("#06\n"); } result = but.toByteArray(); } else { throw new Exception("#08\n HttpResponse " + response); } } else { throw new Exception("#09\nConnection is Null"); } } catch (Exception ex) { throw new Exception(ex.getMessage()); } finally { try { if (con != null) { con.close(); } con = null; if (is != null) { is.close(); } if (but != null) { but.close(); } } catch (IOException ex1) { throw new Exception("#11\n"); } } } private void post() throws Exception { HttpConnection con = null; InputStream is = null; DataOutputStream os = null; ByteArrayOutputStream but = null; try { try { con = (HttpConnection) Connector.open(url); con.setRequestMethod(HttpConnection.POST); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); os = con.openDataOutputStream(); //#if debug == 1 System.out.println(prepareRequest()); //#endif os.write(prepareRequest().getBytes()); } catch (IOException w) { throw new Exception("#01\n" + w.getMessage()); } if (con != null) { int response = 0; try { response = con.getResponseCode(); } catch (Exception ex) { throw new Exception("#02\n" + ex.getMessage()); } if (response == HttpConnection.HTTP_OK) { try { is = con.openInputStream(); } catch (IOException ex) { throw new Exception("#03\nCan't OpenInputStream"); } but = new ByteArrayOutputStream(); try { //===Read response=== int ch = 0; ch = is.read(); while (ch != -1) { but.write(ch); ch = is.read(); } } catch (Exception e) { throw new Exception("#04\nRead Error"); } try { but.flush(); } catch (Exception e) { throw new Exception("#06\n"); } result = but.toByteArray(); } else { throw new Exception("#08\nHttpResponse " + response); } } } catch (Exception ex) { throw new Exception(ex.getMessage()); } finally { try { if (con != null) { con.close(); } } catch (IOException ex1) { } try { if (is != null) { is.close(); } } catch (IOException ex2) { } try { if (but != null) { but.close(); } } catch (IOException ex3) { } try { if (os != null) { os.close(); } } catch (IOException ex4) { } } } /** * * @return byte[] - data from server in byte[] */ public byte[] getByteResult() { return result; } public boolean isData(String response){ return getByteResult() == null || getByteResult().length == 0 || response.equals(getResult()); } /** * * @return String - data from server in String */ public String getResult() { if (result != null && result.length > 0) { return new String(result); } return null; } public boolean isActive() { return active; } public void setActive(boolean isActive) { this.active = isActive; } public void setParam(String variable, String value) { this.params.put(variable, value); } }
This entry was written by admin , posted on Friday January 23 2009at 06:01 am , filed under J2ME and tagged , , , . Bookmark the permalink . Post a comment below or leave a trackback: Trackback URL.

Leave a Reply

You must be logged in to post a comment.