0
我想知道如何將CURL中的示例轉換爲JSONObject。我在互聯網上嘗試過很多例子,但我沒有弄清楚DATA參數怎麼能發送。我該如何創建curl示例所要求的相同請求(JAVA ANDROID)
捲曲:
$ curl https://api.iugu.com/v1/payment_token \
-d "account_id=xxxxxx" \
-d "method=credit_card" \
-d "data[number]=4111111111111111" \
-d "data[verification_value]=123" \
-d "data[first_name]=Joao" \
-d "data[last_name]=Silva" \
-d "data[month]=12" \
-d "data[year]=2013"
參考:https://iugu.com/referencias/api#criar-um-token
我與參數應用並獲得ID爲回報:
try {
URL url = new URL(urlString);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
String userCredentials = "xxxxxxxx"; //TOKEN
String basicAuth = "Basic " + Base64.encodeToString((userCredentials).getBytes(), Base64.DEFAULT);
urlConnection.setRequestProperty ("Authorization", basicAuth);
JSONObject jsonObject = new JSONObject();
jsonObject.put("account_id", params[1]);
jsonObject.put("method", params[2]);
jsonObject.put("test", params[3]);
jsonObject.put("data[number]", params[4]);
jsonObject.put("data[verification_value]", params[5]);
jsonObject.put("data[first_name]", params[6]);
jsonObject.put("data[last_name]", params[7]);
jsonObject.put("data[month]", params[8]);
jsonObject.put("data[year]", params[9]);
OutputStreamWriter os= new OutputStreamWriter(urlConnection.getOutputStream());
os.write(jsonObject.toString());
os.flush();
int responseCode = urlConnection.getResponseCode();
Log.d(TAG, "IUGU responsecode " + responseCode);
StringBuilder responseStrBuilder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String inputStr = null;
while ((inputStr = reader.readLine()) != null)
responseStrBuilder.append(inputStr);
InJsonObject = new JSONObject(responseStrBuilder.toString());
id = InJsonObject.get("id").toString();
Log.d(TAG, "IUGU id " + id);
os.close();
太好了!解決了我的問題。謝謝安東! – herbertxm