我想将数据从 Android 应用程序发送到远程服务器。我尝试将数据作为样本发送到服务器,但它正在工作。我正在下面上传我的代码。我不确定,但可能是我的数据发送格式错误。
链接需要显示成功消息。不幸的是它没有显示任何变化。
public void postData() throws JSONException {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.145/tracker/index.php/json/add_task");
JSONObject json = new JSONObject();
try {
// JSON data:
json.put("task_title", "Fahmi Rahman");
json.put("task_details", "sysdev");
JSONArray postjson=new JSONArray();
postjson.put(json);
// Post the data:
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
// Execute HTTP Post Request
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
// for JSON:
if(response != null)
{
InputStream is = response.getEntity().getContent();
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();
}
}
//text = sb.toString();
}
//tv.setText(text);
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
我需要发送这个格式的数据
{"task":{
"task_title":"All json formate",
"task_details":"View All task list, View task list by user id, Add new task"}}
最佳答案
JsonObject 格式:
分配新的内部 JsonObject
JSONObject jInnerObject = new JSONObject();
在内部 JsonObject 中插入键和值
jInnerObject.put("task_title", "Fahmi Rahman");
jInnerObject.put("task_details", "sysdev");
分配新的外部 JsonObject
JSONObject jOuterObject = new JSONObject();
在外部对象中插入带有键的内部对象
jOuterObject.put("task", jInnerObject);
Log.i("JSonServerObject", jOuterObject.toString());
完成
关于android - 使用 JSON 将数据发送到 Android 中的服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31097004/