你只需要导入这个
import org.json.JSONObject;
constructing the String that you want to send
JSONObject param=new JSONObject();
JSONObject post=new JSONObject();
我使用两个对象,因为你可以在另一个对象中有一个 jsonObject
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");
然后我把post json放在另一个这样的里面
param.put("post",post);
这是我用来发出请求的方法
makeRequest(param.toString());
public JSONObject makeRequest(String param)
{
try
{
设置连接
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();
设置输出流
dataOutputStream = new DataOutputStream(connection.getOutputStream());
我用它在 logcat 中查看我发送的内容
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;
这里构造了字符串
while ((line = reader.readLine()) != null)
{
result.append(line);
}
我使用这个日志来查看响应中的内容
Log.d("INPUTSTREAM: ",result.toString());
使用包含服务器响应的字符串实例化一个 json
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;
}