Thursday, November 14, 2013

android json with post method response

try {
           
         URL url = new URL("http://www.htmlgoon.com/api/POST_JSON_Service.php");
           
            JSONObject jo = new JSONObject();

           
            jo.put("firstname", "abc");
            jo.put("lastname", "xyz");
            jo.put("city", "Bengalore");

           
//            jo.put("userID", "6268656283cfcc32b07340e5a9d7aceec747b316");
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url.toURI());
            // // Set up the header types needed to properly transfer JSON
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Accept", "JSON");
            httpPost.setHeader("Accept-Encoding", "application/json");
            httpPost.setHeader("Accept-Language", "en-US");
            //
            // // Prepare JSON to send by setting the entity
            httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));
            //

            // //
            // // Execute POST
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

            Log.d("===========", "HTTP: OK");
        } catch (Exception e) {
            Log.e("*********", "Error in http connection " + e.toString());
        }
        //
        // // Convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "UTF-8"));

            sb = new StringBuilder();

            String line = null;
            //
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            is.close();

            result = sb.toString();
            //
            Log.e("&&&&&&&&&&&&", "result=" + result);
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                    .show();
        }
        // END Convert response to string

api testing webtie