我非常坚持将 PHP 服务器请求转换为等效的 Java 请求。这是包含我需要在 JAVA 中复制并从 Android 设备发送的 JSON 对象的代码:
$(".unableprocess").click(function() {
if (!confirm("Confirm not able to process...!")) {
return false;
} else {
var item_id = $(this).attr('data-id');
var table_id = $(this).attr('table-id');
var data = {
BookOrders: {
item_id: item_id,
table_id: table_id
}
};
$.ajax({
url: //MY URL HERE ,
type: "POST",
data: data,
success: function(evt, responseText) {
location.reload();
}
});
}
});
这是我的 Java 类,它尝试执行相同的功能。该类扩展了 AsyncTask 并且所有网络交互都发生在 doInBackground() 方法中。这是我的代码:
@Override
protected Boolean doInBackground(String... arg0) {
try{
HashMap<String, String> hashMap = new HashMap<String,String>();
JSONObject jsonObject = new JSONObject();
int statusCode;
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(tableMateCannotProcessURL);
// JSON object creation begins here:
jsonObject.accumulate("item_id",this.itemId);
jsonObject.accumulate("table_id",this.tableId);
JSONObject jObject = new JSONObject();
jObject.accumulate("BookOrders", jsonObject);
// JSON object ends here
Log.v("ATOMIC BLAST",jObject.toString());
String json = jObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
HttpResponse response = client.execute(httpPost);
statusCode = response.getStatusLine().getStatusCode();
Integer statusCodeInt = new Integer(statusCode);
Log.v("HTTPResponse",statusCodeInt.toString());
String result= "";
StringBuilder builder = new StringBuilder();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = builder.toString();
}
else {
Log.e("==>", "Failed to download file");
}
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
我创建的 JSON 对象在将其打印到控制台后如下所示:
{"BookOrders":{"table_id":"1","item_id":"2"}}
将此对象发布到服务器后,我没有得到预期的响应。在 JAVA 中将 JSON 对象转换为等效 JSON 对象的正确方法是什么?任何指导、方向或解决方案将不胜感激。