How to send JSONObject by HttpPost?

by veen » Sat, 26 Sep 2009 02:17:26 GMT


Sponsored Links
 I need to send http request with the following view:

POST /device/api/login HTTP/1.1
Content-Type: text/json

{"login":"LOGIN","password":"PASSWORD"}

[my code]
                        DefaultHttpClient hClient = new
DefaultHttpClient();
                        HttpPost post = new HttpPost(host + 
"/device/api/login");

                        post.setHeader("Content-Type", "text/json");

                        JSONObject jo = new JSONObject();
                        jo.put("login", login);
                        jo.put("password", password);
                        String  joSt = jo.toString();

                        BasicHttpEntity be = new BasicHttpEntity();
                        byte bytes[] = joSt.getBytes();

                        be.setContent(new ByteArrayInputStream(bytes));
                        post.setEntity(be);

                        HttpResponse response = hClient.execute(post);

                        hClient.getConnectionManager().shutdown();
[/my code]
It doesn't work. Could you help me to figure out what's wrong?

--~--~---------~--~----~------------~-------~--~----~



How to send JSONObject by HttpPost?

by Alok Kulkarni » Sat, 26 Sep 2009 03:25:03 GMT


 njoy....
URL url = new URL(serverURL);

// open the conncetion
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();

// Let the run-time system (RTS) know that we want input.
connection.setDoInput(true);
// Let the RTS know that we want to do output
connection.setDoOutput(true);
// No caching, we want the real thing
connection.setUseCaches(false);
// set the content type property
connection.setRequestProperty("Content-type",strContenttype);

// set request method
connection.setRequestMethod("POST");
// create the post body to send
String content = credDevPair.toString();
Log.i("Request ====....... ",content);
DataOutputStream printout = new DataOutputStream (
connection.getOutputStream () );

// send the data
printout.writeBytes(content);
printout.flush();
printout.close();
String output =
convertStreamToString(connection.getInputStream());
Log.i("Response 1....... ",output);
// A Simple JSONObject Creation
JSONObject json=new JSONObject(output);

Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</jsonobject>");

// A Simple JSONObject Parsing
JSONArray nameArray=json.names();
JSONArray valArray=json.toJSONArray(nameArray);
for(int i=0; i<valArray.length() ;i++)
{

Log.i("Praeda","<jsonname"+i+">\n"+nameArray.getString(i)+"\n</jsonname"+i+">\n"


+"<jsonvalue"+i+">\n"+valArray.getString(i)+"\n</jsonvalue"+i+">");
}
//BufferedReader input = new BufferedReader ( new
InputStreamReader(connection.getInputStream()) );

}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();

}catch(Exception ex)
{

}
}

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();
}
}
return sb.toString();
}

Please put in the requred content type, server url..
Thanks, Alok

On Fri, Sep 25, 2009 at 2:01 AM, veen <veensmail...@gmail.


Sponsored Links


Other Threads

1. trying to connect a onListItemClick to a contact (newbie)

Hello,
I am trying to create a simple hello world application and then dial the
selected contacts number from my contacts.  I can seem to figure out how to
connect the selected user to his phone number.  I have been playing with
this for a few days.  Any help would be appreciated.

    @Override
    // the class that is called every time the user clicks something
    protected void onListItemClick(ListView l, View v, int position, long
id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);

        // the reflections of a applications intent to perform some activity
        // in this case a call action to dial the phone
        Intent i = new Intent(Intent.ACTION_CALL);
        Cursor c = (Cursor) mAdapter.getItem(position);

        //get the lookup key for the phone number
        String phoneId = c.getString(c.getColumnIndex(Contacts.LOOKUP_KEY));

        //find the phone number in ContactsContract

        //set the phone number in the intent to dial
        //i.setData(phoneNum);

        // Causes the dialer to appear on the screen and initiate the phone
call
        //startActivity(i);
    }
}

-- 
"If men were angels, no government would be necessary."
--Madison

-- 

2. Not sure if this is a bug? RelativeLayout + fill_parent

Found a quirk and wondering if I'm missing something. I have a View inside
of a RelativeLayout which has its background color set at runtime. I'm
finding in this case I need to set an explicit height otherwise the view
will not show. i.e. if I set the layout_height="fill_parent", it's not
visible.

<RelativeLayout
   android:id="@+id/detail_header"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical"
   android:background="@color/detail_task_header_bg">

      <View
         android:id="@+id/detail_account_color"
         android:layout_width="5dip"
         android:layout_height="135dip"
         android:layout_alignTop="@id/detail_header"
         android:layout_alignLeft="@id/detail_header" />

-- 

3. Make Activity not show

4. Lagi coba wildfire..

5. long process of automatic configuration after installation

6. EVO failing in MediaPlayer

7. Making Android development more enjoyable