我正在尝试转换Unirest
HttpResponse<String> response = Unirest.post("https://api.tap.company/v2/charges")
.header("authorization", "Bearer sk_test_XKokBfNWv6FIYuTMg5sLPjhJ")
.header("content-type", "application/json")
.body("{\"amount\":1,\"currency\":\"KWD\",\"receipt\":{\"email\":false,\"sms\":true},\"customer\":{\"first_name\":\"test\",\"phone\":{\"country_code\":\"965\",\"number\":\"50000000\"}},\"source\":{\"id\":\"src_kw.knet\"},\"redirect\":{\"url\":\"http://your_website.com/redirect_url\"}}")
.asString();
排球
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://api.tap.company/v2/charges";
StringRequest TapREQUEST = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override public void onResponse(String response) {
Log.w("OnResponse:", response);
}
}, new Response.ErrorListener() {
@Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); }
}) {
@Override public Map<String, String> getHeaders() {
Map<String,String> headers = new HashMap<>();
headers.put("content-type", "application/json");
headers.put("authorization", "Bearer sk_test_XKokBfNWv6FIYuTMg5sLPjhJ");
//String auth = "Bearer " + Base64.encodeToString("sk_test_XKokBfNWv6FIYuTMg5sLPjhJ".getBytes(), Base64.DEFAULT);
//headers.put("authorization", auth);
return headers;
}
@Override protected Map<String,String> getParams() {
Map<String,String> params = new HashMap<>();
params.put("amount", String.valueOf(9.500));
params.put("currency","KWD");
params.put("receipt","{'email':false,'sms':true}");
params.put("customer",":{'first_name':'test','phone':{'country_code':'965','number':'50000000'}}");
params.put("source","{'id':'src_kw.knet'}");
params.put("redirect",":{'url':'http://ib7ar.com'}");
return params;
}
};
queue.add(TapREQUEST);
但是我明白了 E / Volley:[396] BasicNetwork.performRequest:https://api.tap.company/v2/charges
的意外响应代码400当我点击链接时,我得到
{“错误”:[{“代码”:“ 2107”,“描述”:“需要授权”}}}
答案 0 :(得分:0)
您必须以其他方式设置身体参数。让我们创建返回正确字符串的方法:
@NotNull
private JSONObject getJsonObject() {
JSONObject params = new JSONObject();
try {
params.put("amount", "1");
params.put("currency", "KWD");
JSONObject receipt = new JSONObject();
receipt.put("email", "false");
receipt.put("sms", "true");
params.put("receipt", receipt);
JSONObject customer = new JSONObject();
customer.put("first_name", "test");
JSONObject phone = new JSONObject();
phone.put("country_code", "965");
phone.put("number", "50000000");
customer.put("phone", phone);
params.put("customer", customer);
JSONObject id = new JSONObject();
id.put("id", "src_kw.knet");
params.put("source", id);
JSONObject url = new JSONObject();
url.put("url", "http://ib7ar.com");
params.put("redirect", url);
} catch (JSONException e) {
e.printStackTrace();
}
return params;
}
现在,您需要getParams()
方法来代替getBody()
:
@Override
public byte[] getBody() {
try {
return getJsonObject().toString().getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}