Skip to content Skip to sidebar Skip to footer

Android Get And Post Request

Can anyone point me to a good implementation of a way to send GET and POST Requests. They are alot of ways to do these, and i am looking for the best implementation. Secondly is th

Solution 1:

You can use the HttpURLConnection class (in java.net) to send a POST or GET HTTP request. It is the same as any other application that might want to send an HTTP request. The code to send an Http Request would look like this:

import java.net.*;
import java.io.*;
publicclassSendPostRequest {
  publicstaticvoidmain(String[] args)throws MalformedURLException, IOException {
    URLreqURL=newURL("http://www.stackoverflow.com/"); //the URL we will send the request toHttpURLConnectionrequest= (HttpURLConnection) (reqUrl.openConnection());
    Stringpost="this will be the post data that you will send"
    request.setDoOutput(true);
    request.addRequestProperty("Content-Length", Integer.toString(post.length)); //add the content length of the post data
    request.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //add the content type of the request, most post data is of this type
    request.setMethod("POST");
    request.connect();
    OutputStreamWriterwriter=newOutputStreamWriter(request.getOutputStream()); //we will write our request data here
    writer.write(post);
    writer.flush();
  }
}

A GET request will look a little bit different, but much of the code is the same. You don't have to worry about doing output with streams or specifying the content-length or content-type:

import java.net.*;
import java.io.*;

publicclassSendPostRequest {
  publicstaticvoidmain(String[] args)throws MalformedURLException, IOException {
    URLreqURL=newURL("http://www.stackoverflow.com/"); //the URL we will send the request toHttpURLConnectionrequest= (HttpURLConnection) (reqUrl.openConnection());
    request.setMethod("GET");
    request.connect();

  }
}

Solution 2:

I prefer using dedicated class to do GET/POST and any HTTP connections or requests. Moreover I use HttpClient to execute these GET/POST methods.

Below is sample from my project. I needed thread-safe execution so there is ThreadSafeClientConnManager.

There is an example of using GET (fetchData) and POST (sendOrder)

As you can see execute is general method for executing HttpUriRequest - it can be POST or GET.

publicfinalclassClientHttpClient {

privatestatic DefaultHttpClient client;
privatestatic CookieStore cookieStore;
privatestatic HttpContext httpContext;

static {
    cookieStore = newBasicCookieStore();
    httpContext = newBasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    client = getThreadSafeClient();
    HttpParamsparams=newBasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, AppConstants.CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, AppConstants.SOCKET_TIMEOUT);
    client.setParams(params);
}

privatestatic DefaultHttpClient getThreadSafeClient() {
    DefaultHttpClientclient=newDefaultHttpClient();
    ClientConnectionManagermgr= client.getConnectionManager();
    HttpParamsparams= client.getParams();
    client = newDefaultHttpClient(newThreadSafeClientConnManager(params, mgr.getSchemeRegistry()),
            params);
    return client;
}

privateClientHttpClient() {
}

publicstatic String execute(HttpUriRequest http)throws IOException {
    BufferedReaderreader=null;
    try {
        StringBuilderbuilder=newStringBuilder();
        HttpResponseresponse= client.execute(http, httpContext);
        StatusLinestatusLine= response.getStatusLine();
        intstatusCode= statusLine.getStatusCode();
        HttpEntityentity= response.getEntity();
        InputStreamcontent= entity.getContent();
        reader = newBufferedReader(newInputStreamReader(content, CHARSET));
        Stringline=null;
        while((line = reader.readLine()) != null) {
            builder.append(line);
        }

        if(statusCode != 200) {
            thrownewIOException("statusCode=" + statusCode + ", " + http.getURI().toASCIIString()
                    + ", " + builder.toString());
        }

        return builder.toString();
    }
    finally {
        if(reader != null) {
            reader.close();
        }
    }
}


publicstatic List<OverlayItem> fetchData(Info info)throws JSONException, IOException {
    List<OverlayItem> out = newLinkedList<OverlayItem>();
    HttpGetrequest= buildFetchHttp(info);
    Stringjson= execute(request);
    if(json.trim().length() <= 2) {
        return out;
    }
    try {
        JSONObjectresponseJSON=newJSONObject(json);
        if(responseJSON.has("auth_error")) {
            thrownewIOException("auth_error");
        }
    }
    catch(JSONException e) {
        //ok there was no error, because response is JSONArray - not JSONObject
    }

    JSONArrayjsonArray=newJSONArray(json);
    for(inti=0; i < jsonArray.length(); i++) {
        JSONObjectchunk= jsonArray.getJSONObject(i);
        ChunkParserparser=newChunkParser(chunk);
        if(!parser.hasErrors()) {
            out.add(parser.parse());
        }
    }
    return out;
}

privatestatic HttpGet buildFetchHttp(Info info)throws UnsupportedEncodingException {
    StringBuilderbuilder=newStringBuilder();
    builder.append(FETCH_TAXIS_URL);
    builder.append("?minLat=" + URLEncoder.encode("" + mapBounds.getMinLatitude(), ENCODING));
    builder.append("&maxLat=" + URLEncoder.encode("" + mapBounds.getMaxLatitude(), ENCODING));
    builder.append("&minLon=" + URLEncoder.encode("" + mapBounds.getMinLongitude(), ENCODING));
    builder.append("&maxLon=" + URLEncoder.encode("" + mapBounds.getMaxLongitude(), ENCODING));
    HttpGetget=newHttpGet(builder.toString());
    return get;
}

publicstaticintsendOrder(OrderInfo info)throws IOException {
    HttpPostpost=newHttpPost(SEND_ORDER_URL);
    List<NameValuePair> nameValuePairs = newArrayList<NameValuePair>(1);
    nameValuePairs.add(newBasicNameValuePair("id", "" + info.getTaxi().getId()));
    nameValuePairs.add(newBasicNameValuePair("address", info.getAddressText()));
    nameValuePairs.add(newBasicNameValuePair("name", info.getName()));
    nameValuePairs.add(newBasicNameValuePair("surname", info.getSurname()));
    nameValuePairs.add(newBasicNameValuePair("phone", info.getPhoneNumber()));
    nameValuePairs.add(newBasicNameValuePair("passengers", "" + info.getPassengers()));
    nameValuePairs.add(newBasicNameValuePair("additionalDetails", info.getAdditionalDetails()));
    nameValuePairs.add(newBasicNameValuePair("lat", "" + info.getOrderLocation().getLatitudeE6()));
    nameValuePairs.add(newBasicNameValuePair("lon", "" + info.getOrderLocation().getLongitudeE6()));
    post.setEntity(newUrlEncodedFormEntity(nameValuePairs));

    Stringresponse= execute(post);
    if(response == null || response.trim().length() == 0) {
        thrownewIOException("sendOrder_response_empty");
    }

    try {
        JSONObjectjson=newJSONObject(response);
        intorderId= json.getInt("orderId");
        return orderId;
    }
    catch(JSONException e) {
        thrownewIOException("sendOrder_parsing: " + response);
    }
}

EDIT

The execute method is public because sometimes I use custom (or dynamic) GET/POST requests.

If you have URL object you can pass to execute method:

HttpGetrequest=newHttpGet(url.toString());
execute(request);

Solution 3:

As you said: the GET-Parameters are in the URL - So you can use a loadUrl() on your Webview to send them.

[..].loadUrl("http://www.example.com/data.php?param1=value1&param2=value2&...");

Solution 4:

The developer training docs have a good example on GET requests. You're responsible for adding the query parameters to the URL.

Post is similar, but as you said, quite different. The HttpConnectionURLConnection class can do both, and it's easy to just set the post body with an output stream.

Solution 5:

protected String doInBackground(String... strings) {
        Stringresponse=null;
        Stringdata=null;
        try {
            data = URLEncoder.encode("CustomerEmail", "UTF-8")
                    + "=" + URLEncoder.encode(username, "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Stringurl= Constant.URL_FORGOT_PASSWORD;// this is url 
        response = ServiceHandler.postData(url,data);
        if (response.equals("")){
            return response;
        }else {
            return response;
        }

    }


publicstatic String postData(String urlpath,String data){

    Stringtext="";
    BufferedReader reader=null;
    try
    {
        // Defined URL  where to send dataURLurl=newURL(urlpath);

        // Send POST data requestURLConnectionconn= url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriterwr=newOutputStreamWriter(conn.getOutputStream());
        wr.write( data );
        wr.flush();

        // Get the server response
        reader = newBufferedReader(newInputStreamReader(conn.getInputStream()));
        StringBuildersb=newStringBuilder();
        Stringline=null;

        // Read Server Responsewhile((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        text = sb.toString();
        return text;
    }
    catch(Exception ex)
    {
    }
    finally
    {
        try
        {
            reader.close();
        }
        catch(Exception ex) {}
    }
    return text;
}

Post a Comment for "Android Get And Post Request"