![](/img/trans.png)
[英]Android Volley - make POST with body and url parameters - getParams and getBody at the same time
[英]Ion POST as url parameters and not JSON body Android
我想使用參數而不是JSON正文發布到服務器API。
我可以實現這一點:
JsonObject json = new JsonObject();
json.addProperty("u_id", "XXX");
json.addProperty("emp_id", "XXX");
json.addProperty("lat", Double.toString(lat));
json.addProperty("lon", Double.toString(lon));
json.addProperty("paper", "5");
json.addProperty("plastic", "10");
json.addProperty("mode", "cash");
json.addProperty("status", "init");
Ion.with(getApplicationContext())
.load(getString(R.string.url)+"/transaction")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
@Override
public void onCompleted(Exception e, JsonObject result) {
if (e != null) {
Toast.makeText(getBaseContext(), "Data : " + e.getStackTrace(), Toast.LENGTH_LONG).show();
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
progress.dismiss();
}
});
Toast.makeText(getBaseContext(), "Pickup added successfully! We will contact you soon.", Toast.LENGTH_LONG).show();
}
}
});
但是我想通過POST到達http://someserver.com/transaction/<u_id>/<emp_id>/22.56/88.45/5/10/cash/init
來實現相同的目的,其中我的服務器已准備好處理參數。
無論如何,Koushik Dutta(@koush)的庫是很棒且異步的。 愛它。
這是可行的,但前提是您手動構造了請求url。
POST請求的請求數據應該進入請求主體,由setJsonObjectBody()
。 url只是POST請求應發送到的端點。
比喻
如果http://someserver.com/transaction
是您居住的城市的名稱,則/<u_id>/<emp_id>/22.56/88.45/5/10/cash/init
是您的房子的地址,而json
是送到您家的包裹。
您可以指定將包裹發送到的地址,但不要在地址標簽上放置有關包裹內容的信息。 這些是2種單獨的數據類型,應區別對待。
因此,你應該做這樣的事情
JsonObject json = new JsonObject();
json.addProperty("lat", Double.toString(lat));
json.addProperty("lon", Double.toString(lon));
json.addProperty("paper", "5");
json.addProperty("plastic", "10");
json.addProperty("mode", "cash");
json.addProperty("status", "init");
String u_id = "XXX";
String emp_id = "XXX";
String url = getString(R.string.url) + "/transaction/" + u_id + "/" +
emp_id + "/22.56/88.45/5/10/cash/init";
Ion.with(getApplicationContext())
.load(url)
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
@Override
public void onCompleted(Exception e, JsonObject result) {
}
});
請注意,URL中的斜杠可能需要轉義。 從我的頭上不知道。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.