Android sending HTTP POST request to the server

10,812

This will help you:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) throws Exception {

    // Making HTTP request
    try {

        // check for request method
        if (method == "POST") {
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            // new
            HttpParams httpParameters = httpPost.getParams();
            // Set the timeout in milliseconds until a connection is
            // established.
            int timeoutConnection = 10000;
            HttpConnectionParams.setConnectionTimeout(httpParameters,
                    timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT)
            // in milliseconds which is the timeout for waiting for data.
            int timeoutSocket = 10000;
            HttpConnectionParams
                    .setSoTimeout(httpParameters, timeoutSocket);
            // new
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } else if (method == "GET") {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);
            // new
            HttpParams httpParameters = httpGet.getParams();
            // Set the timeout in milliseconds until a connection is
            // established.
            int timeoutConnection = 10000;
            HttpConnectionParams.setConnectionTimeout(httpParameters,
                    timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT)
            // in milliseconds which is the timeout for waiting for data.
            int timeoutSocket = 10000;
            HttpConnectionParams
                    .setSoTimeout(httpParameters, timeoutSocket);
            // new
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        throw new Exception("Unsupported encoding error.");
    } catch (ClientProtocolException e) {
        throw new Exception("Client protocol error.");
    } catch (SocketTimeoutException e) {
        throw new Exception("Sorry, socket timeout.");
    } catch (ConnectTimeoutException e) {
        throw new Exception("Sorry, connection timeout.");
    } catch (IOException e) {
        throw new Exception("I/O error(May be server down).");
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        throw new Exception(e.getMessage());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        throw new Exception(e.getMessage());
    }

    // return JSON String
    return jObj;

}
 }

You can use the above class like this: eg:

public class GetName extends AsyncTask<String, String, String> {
String imei = "abc";
JSONParser jsonParser = new JSONParser();

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

protected String doInBackground(String... args) {
    String name = null;
    String URL = "http://192.168.2.5:8000/mobile/";
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("username", mUsername));
    params.add(new BasicNameValuePair("password", mPassword));
    JSONObject json;
    try {
        json = jsonParser.makeHttpRequest(URL, "POST", params);
        try {
            int success = json.getInt(Settings.SUCCESS);
            if (success == 1) {
                name = json.getString("name");
            } else {
                name = null;
            }
        } catch (JSONException e) {
            name = null;
        }
    } catch (Exception e1) {
    }
    return name;
}

protected void onPostExecute(String name) {
    Toast.makeText(mcontext, name, Toast.LENGTH_SHORT).show();
 }
 }


How to use it:
Just create new JSONParse class by copying about class code. Then you can call it any where in your application as shown in second code(Customize the second code).
You need to give manifest permission:

    <uses-permission android:name="android.permission.INTERNET" />

No need to check SSL certificate.

Share:
10,812
SibinF
Author by

SibinF

Updated on June 05, 2022

Comments

  • SibinF
    SibinF almost 2 years

    I'm creating an application that connects to the cakePHP website I create a default HTTP client and send a HTTP POST request to the server. The data is coming from the server in json format, and in the client side I take the value from the json array, this is my project structure. Below I show some code that I used to connect with server

            try{
                 HttpClient httpclient = new DefaultHttpClient();
                 HttpPost httppost = new HttpPost("http://10.0.2.2/XXXX/logins/login1");
    
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
            response = httpclient.execute(httppost);
            StringBuilder builder = new StringBuilder();
                   BufferedReader   reader = new BufferedReader
    
                (new     InputStreamReader(response.getEntity().getContent(), "UTF-8"));
    
                  for (String line = null; (line = reader.readLine()) != null;) 
    
                        {
                        builder.append(line).append("\n");
                        }
    
                  JSONTokener   tokener = new JSONTokener(builder.toString());
                  JSONArray  finalResult = new JSONArray(tokener);
                  System.out.println("finalresulttttttt"+finalResult.toString());
                  System.out.println("finalresul length"+finalResult.length());
                    Object type = new Object();
    
                  if (finalResult.length() == 0 && type.equals("both")) 
                {
            System.out.println("null value in the json array");
    
    
                    }
        else {
    
               JSONObject   json_data = new JSONObject();
    
                for (int i = 0; i < finalResult.length(); i++) 
                   {
                       json_data = finalResult.getJSONObject(i);
    
                       JSONObject menuObject = json_data.getJSONObject("Userprofile");
    
                       group_id= menuObject.getString("group_id");
                       id = menuObject.getString("id");
                       name = menuObject.getString("name");
                    }
                        }
                            }
    
    
                      catch (Exception e) {
                   Toast.makeText(FirstMain.this,"exceptionnnnn",Toast.LENGTH_LONG).show();
                     e.printStackTrace();
                        }
    

    My problem is

    1. I need to connect every page with the server, for that I need to write the code every time in my all activity, is there any other way to make a connection to the server and send a request from every activity? The concept of an interface is something like....
    2. Is there any class that is supplied by the android library for connecting to the server?
    3. Is any need to check all verification such as an SSL certificate such as in the client-side?

    4. Are there any additional requirements needed for connecting to a server from android?

    5. What is the need of implementing services like SOAP REST for interaction with the server

    I'm a fresher in this field.. please give me answer for my doubts.. And please support me...

  • SibinF
    SibinF about 11 years
    Hi Vishal, I have another doubt hop you can solve this.. in my program i have a main class that extends the Activity class and i need to write- public class GetName extends AsyncTask<String, String, String> - this class(you are provided) in some onclick function . the how to call this class?? i need to perform this action only when someone click a button, thats why i written in the onclick function
  • SibinF
    SibinF about 11 years
    Hi....when i extend my class using AsyncTask<String, String, String> - it showing error . AndroidRuntime(463): Uncaught handler: thread main exiting due to uncaught exception E/AndroidRuntime(463): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.cakeconnect/com.example.cakeconnec‌​t.DeleteAllocatedRCa‌​rd}: java.lang.ClassCastException: \com.example.cakeconnect.DeleteAllocatedRCard , I need to extend the Activity class. how it is possible
  • SibinF
    SibinF about 11 years
    Hi Vishal, can u understand my problem? in every activity , i need to communicate with the server. my problem is each class is extending the main activity , then how to extend this -syncTask<String, String, String>
  • SibinF
    SibinF about 11 years
    iam confusing..please give me a solution
  • Vishal Vijay
    Vishal Vijay about 11 years
    Dude..download this project. Take it as a reference for your current problemhttps://github.com/vishalvijay/Fingerprint-Magic
  • Vishal Vijay
    Vishal Vijay about 11 years
    See server package in above project