Якщо не пізно, я хотів би поділитися своїм кодом
Utils.java:
public static String buildPostParameters(Object content) {
String output = null;
if ((content instanceof String) ||
(content instanceof JSONObject) ||
(content instanceof JSONArray)) {
output = content.toString();
} else if (content instanceof Map) {
Uri.Builder builder = new Uri.Builder();
HashMap hashMap = (HashMap) content;
if (hashMap != null) {
Iterator entries = hashMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
entries.remove(); // avoids a ConcurrentModificationException
}
output = builder.build().getEncodedQuery();
}
}
return output;
}
public static URLConnection makeRequest(String method, String apiAddress, String accessToken, String mimeType, String requestBody) throws IOException {
URL url = new URL(apiAddress);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(!method.equals("GET"));
urlConnection.setRequestMethod(method);
urlConnection.setRequestProperty("Authorization", "Bearer " + accessToken);
urlConnection.setRequestProperty("Content-Type", mimeType);
OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
writer.write(requestBody);
writer.flush();
writer.close();
outputStream.close();
urlConnection.connect();
return urlConnection;
}
MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new APIRequest().execute();
}
private class APIRequest extends AsyncTask<Void, Void, String> {
@Override
protected Object doInBackground(Void... params) {
// Of course, you should comment the other CASES when testing one CASE
// CASE 1: For FromBody parameter
String url = "http://10.0.2.2/api/frombody";
String requestBody = Utils.buildPostParameters("'FromBody Value'"); // must have '' for FromBody parameter
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/json", requestBody);
InputStream inputStream;
// get stream
if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
inputStream = urlConnection.getInputStream();
} else {
inputStream = urlConnection.getErrorStream();
}
// parse stream
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String temp, response = "";
while ((temp = bufferedReader.readLine()) != null) {
response += temp;
}
return response;
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
// CASE 2: For JSONObject parameter
String url = "http://10.0.2.2/api/testjsonobject";
JSONObject jsonBody;
String requestBody;
HttpURLConnection urlConnection;
try {
jsonBody = new JSONObject();
jsonBody.put("Title", "BNK Title");
jsonBody.put("Author", "BNK");
jsonBody.put("Date", "2015/08/08");
requestBody = Utils.buildPostParameters(jsonBody);
urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/json", requestBody);
...
// the same logic to case #1
...
return response;
} catch (JSONException | IOException e) {
e.printStackTrace();
return e.toString();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
// CASE 3: For form-urlencoded parameter
String url = "http://10.0.2.2/api/token";
HttpURLConnection urlConnection;
Map<String, String> stringMap = new HashMap<>();
stringMap.put("grant_type", "password");
stringMap.put("username", "username");
stringMap.put("password", "password");
String requestBody = Utils.buildPostParameters(stringMap);
try {
urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/x-www-form-urlencoded", requestBody);
...
// the same logic to case #1
...
return response;
} catch (Exception e) {
e.printStackTrace();
return e.toString();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
// do something...
}
}