Wednesday, November 30, 2011

making http get response code to get json response

/**
     * This method connects to server through HTTP request .
     */
    private static String connect(String url){

        // Create the httpclient
        //HttpClient httpclient = new DefaultHttpClient();
        DefaultHttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object
        HttpGet httpget = new HttpGet(url);
        Log.e("mSessionId",""+mSessionId);
        //Header h="JSESSIONID";
        //HttpRequest req=null;
        //req.addHeader("JSESSIONID",mSessionId);
   
        httpget.addHeader("JSESSIONID","mSessionId1"+":" +mSessionId);
        httpget.getAllHeaders();
         HeaderElementIterator it1 = new BasicHeaderElementIterator(
                 httpget.headerIterator());
         System.out.println(httpget.getURI());

         while (it1.hasNext()) {
             HeaderElement elem = it1.nextElement();
             System.out.println("session name"+elem.getName() + " = " + elem.getValue());
             NameValuePair[] params = elem.getParameters();
             for (int i = 0; i < params.length; i++) {
                 System.out.println(" " + params[i]);
             }
         }
        // Execute the request
        HttpResponse response;

        // return string
        String returnString = null;

        try {

            // Open the webpage.
            response = httpclient.execute(httpget);

            //        if(response.getStatusLine().getStatusCode() == 200){
            if(true) {
                // Connection was established. Get the content.

                HttpEntity entity = response.getEntity();
                //SetCookie c=new Cookie();
                //SetCookie.setValue(mSessionId);
                response.getAllHeaders();
                Log.e("headers",""+response.getAllHeaders());
                 HeaderElementIterator it = new BasicHeaderElementIterator(
                            response.headerIterator());
                    while (it.hasNext()) {
                        HeaderElement elem = it.nextElement();
                        System.out.println(elem.getName() + " = " + elem.getValue());
                        NameValuePair[] params = elem.getParameters();
                        for (int i = 0; i < params.length; i++) {
                            System.out.println(" " + params[i]);
                        }
                    }
                // If the response does not enclose an entity, there is no need
                // to worry about connection release

                if (entity != null) {
                    // A Simple JSON Response Read
                    InputStream instream = entity.getContent();

                    // Load the requested page converted to a string into a JSONObject.
                    //    JSONObject myAwway = new JSONObject(convertStreamToString(instream));
                    returnString = convertStreamToString(instream);
                    //    Log.e(TAG,"instream  : "+convertStreamToString(instream));
                    //        Log.e(TAG,"myawway  : "+ myAwway);

                    // Get the query value'
                    //String query = myAwway.getString("query");
                    //    JSONObject menuObject =myAwway.getJSONObject("photos");
                    // Make array of the suggestions
                    //        JSONArray suggestions =menuObject.getJSONArray("photo");

                    // Build the return string.
                    //                    returnString = "Found: " + suggestions.length() ;
                    //                for (int i = 0; i < suggestions.length(); i++) {
                    //                    returnString += "\n\t" +(suggestions.getJSONObject(i).getString("id").toString());
                    //                }
                    //    returnString = "Found";
                    // Cose the stream.
                    instream.close();

                }
            }
            else {
                // code here for a response othet than 200.  A response 200 means the webpage was ok
                // Other codes include 404 - not found, 301 - redirect etc...
                // Display the response line.
                returnString = "Unable to load page - " + response.getStatusLine();
            }
            return returnString ; 
        }
        catch (IOException  ex) {
            // thrown by line 80 - getContent();
            // Connection was not established
            returnString = "Connection failed; " + ex.getMessage();
        }
        //        catch (JSONException ex){
        // JSON errors
        //            returnString = "JSON failed; " + ex.getMessage();
        //        }
        return returnString;
    }

    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {

                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Log.e(TAG,"sb string   : "+ sb.toString());
        return sb.toString();
    }
   

No comments:

Post a Comment