To send JSON object in server you have to do the following steps:-
1) Create JSON object
2) Set the header of HttpPost to "Content-Type", "application/json"
3) Now call postJsonObjectToServer method(define below) :-
public static String postJsonObjectToServer(JSONObject jsonObject, String url)
{
final DefaultHttpClient client = new DefaultHttpClient();
HttpPost method=null;
try {
method = new HttpPost(new URI(url));
method.setHeader( "Content-Type", "application/json" );
method.setEntity(new ByteArrayEntity(jsonObject.toString().getBytes("UTF8")));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
HttpResponse res=null;
try
{
if(client!=null)
res = client.execute(method);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(res!=null)
{
HttpEntity entity=res.getEntity();
InputStream input=null;
try {
input = res.getEntity().getContent();
byte[] data = new byte[256];
int len = 0;
int size = 0;
StringBuffer raw = new StringBuffer();
while ( -1 != (len = input.read(data)) )
{
raw.append(new String(data, 0, len));
size += len;
}
input.close();
return raw.toString();
} catch (IllegalStateException e) {
e.printStackTrace();
return "";
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
else
{
return "";
}
}
Call the above method in background thread.
Similarly you can send the JSONArray to the server.
0 Comment(s)