you just need to import this
import org.json.JSONObject;
constructing the String that you want to send
JSONObject param=new JSONObject();
JSONObject post=new JSONObject();
im using two object because you can have an jsonObject within another
post.put("username(here i write the key)","someusername"(here i put the value);
post.put("message","this is a sweet message");
post.put("image","http://localhost/someimage.jpg");
post.put("time": "present time");
then i put the post json inside another like this
param.put("post",post);
this is the method that i use to make a request
makeRequest(param.toString());
public JSONObject makeRequest(String param)
{
try
{
setting the connection
urlConnection = new URL("your url");
connection = (HttpURLConnection) urlConnection.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
connection.setReadTimeout(60000);
connection.setConnectTimeout(60000);
connection.connect();
setting the outputstream
dataOutputStream = new DataOutputStream(connection.getOutputStream());
i use this to see in the logcat what i am sending
Log.d("OUTPUT STREAM " ,param);
dataOutputStream.writeBytes(param);
dataOutputStream.flush();
dataOutputStream.close();
InputStream in = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
here the string is constructed
while ((line = reader.readLine()) != null)
{
result.append(line);
}
i use this log to see what its comming in the response
Log.d("INPUTSTREAM: ",result.toString());
instancing a json with the String that contains the server response
jResponse=new JSONObject(result.toString());
}
catch (IOException e) {
e.printStackTrace();
return jResponse=null;
} catch (JSONException e)
{
e.printStackTrace();
return jResponse=null;
}
connection.disconnect();
return jResponse;
}