Android 步骤 2 异步服务器请求
PayPal Developer Github 存储库中提供了此应用程序的完整示例代码(Android +节点服务器)。
此时已点击 PayPal 未来付款按钮,我们有来自 PayPal SDK 的身份验证代码和元数据 ID,我们需要将这些代码传递到我们的服务器以完成将来的付款流程。
在下面的后台流程中,我们正在做一些事情:
- 我们设置了服务器为
http://10.0.2.2:3000/fpstore
的 URI,它正在命中我们在 localhost 上运行的服务器的/fpstore
端点。 - 然后将设置将要发送的 JSON 对象,其中包含身份验证代码和元数据 ID。
- 然后建立连接。在成功请求(200/201 范围)的情况下,我们可以期待从服务器返回响应。我们读了那个回复,然后又回来了。
- 最后,我们设置了
onPostExecute(...)
方法来处理返回的服务器字符串。在这个例子的情况下,它只是记录。
public class ServerRequest extends AsyncTask<String, Void, String> {
protected String doInBackground(String[] params){
HttpURLConnection connection = null;
try{
//set connection to connect to /fpstore on localhost
URL u = new URL("http://10.0.2.2:3000/fpstore");
connection = (HttpURLConnection) u.openConnection();
connection.setRequestMethod("POST");
//set configuration details
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setAllowUserInteraction(false);
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
//set server post data needed for obtaining access token
String json = "{\"code\": \"" + params[0] + "\", \"metadataId\": \"" + params[1] + "\"}";
Log.i("JSON string", json);
//set content length and config details
connection.setRequestProperty("Content-length", json.getBytes().length + "");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
//send json as request body
OutputStream outputStream = connection.getOutputStream();
outputStream.write(json.getBytes("UTF-8"));
outputStream.close();
//connect to server
connection.connect();
//look for 200/201 status code for received data from server
int status = connection.getResponseCode();
switch (status){
case 200:
case 201:
//read in results sent from the server
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null){
sb.append(line + "\n");
}
bufferedReader.close();
//return received string
return sb.toString();
}
} catch (MalformedURLException ex) {
Log.e("HTTP Client Error", ex.toString());
} catch (IOException ex) {
Log.e("HTTP Client Error", ex.toString());
} catch (Exception ex) {
Log.e("HTTP Client Error", ex.toString());
} finally {
if (connection != null) {
try{
connection.disconnect();
} catch (Exception ex) {
Log.e("HTTP Client Error", ex.toString());
}
}
}
return null;
}
protected void onPostExecute(String message){
//log values sent from the server - processed payment
Log.i("HTTP Client", "Received Return: " + message);
}
}