作者:1234567山02 | 来源:互联网 | 2023-10-12 20:33
方法一:使用HttpsURLConnection(响应速度比方法二快)publicstaticJSONObjectverifyReceipt1(Stringrecepit){
方法一:使用HttpsURLConnection(响应速度比方法二快)
public static JSONObject verifyReceipt1(String recepit) {
return verifyReceipt1("https://buy.itunes.apple.com/verifyReceipt", recepit);
}
public static JSONObject verifyReceipt1(String url, String receipt) {
try {
HttpsURLConnection cOnnection= (HttpsURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setAllowUserInteraction(false);
PrintStream ps = new PrintStream(connection.getOutputStream());
ps.print("{\"receipt-data\": \"" + receipt + "\"}");
ps.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str;
StringBuffer sb = new StringBuffer();
while ((str = br.readLine()) != null) {
sb.append(str);
}
br.close();
String resultStr = sb.toString();
JSONObject result = JSONObject.parseObject(resultStr);
if (result != null && result.getInteger("status") == 21007) {
return verifyReceipt1("https://sandbox.itunes.apple.com/verifyReceipt", receipt);
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
方法二:使用HttpClient
public static JSONObject verifyReceipt2(String receipt) {
return verifyReceipt2("https://buy.itunes.apple.com/verifyReceipt", receipt);
}
public static JSONObject verifyReceipt2(String url, String receipt) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
JSONObject data = new JSONObject();
data.put("receipt-data", receipt);
StringEntity entity = new StringEntity(data.toJSONString());
entity.setContentEncoding("utf-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpResponse respOnse= httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
String resultStr = EntityUtils.toString(httpEntity);
JSONObject result = JSONObject.parseObject(resultStr);
httpPost.releaseConnection();
if (result.getInteger("status") == 21007) {
return verifyReceipt2("https://sandbox.itunes.apple.com/verifyReceipt", receipt);
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}