Я хочу отправить объект json {"PersonID": "124", "DeviceID": "123", "ExpID": "1234", "ID": "4566"} по определенному URL-адресу API Azure Rest
Я пытался использовать приведенный ниже код, он работает для URL- http://hmkcode.appspot.com/jsonservlet, но не для URL-адреса моего API AZURE REST
MainActivity.java
private String httpPost(String myUrl) throws IOException, JSONException
{
String result = "";
URL url = new URL(myUrl);
// 1. create HttpURLConnection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
// 2. build JSON object
JSONObject jsonObject = buidJsonObject();
// 3. add JSON content to POST request body
setPostRequestContent(conn, jsonObject);
// 4. make POST request to the given URL
conn.connect();
// 5. return response message
return conn.getResponseMessage()+"";
}
private class HTTPAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
try {
return httpPost(urls[0]);
} catch (JSONException e) {
e.printStackTrace();
return "Error!";
}
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
//tvResult.setText(result);
}
}
public void send(View view) {
Toast.makeText(this, "Clicked", Toast.LENGTH_SHORT).show();
// perform HTTP POST request
new HTTPAsyncTask().execute("URL");
}
private JSONObject buidJsonObject() throws JSONException {
String w= "test";
String a= "ABCD";
JSONObject jsonObject = new JSONObject();
jsonObject.put("PersonID",token);
jsonObject.put("DeviceID", Settings.Secure.ANDROID_ID);
jsonObject.put("ExpID", w);
jsonObject.put("ID", a);
return jsonObject;
}
private void setPostRequestContent(HttpURLConnection conn, JSONObject jsonObject) throws IOException {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(jsonObject.toString());
Log.i(MainActivity.class.toString(), jsonObject.toString());
writer.flush();
writer.close();
os.close();
}
Activity_Main.xml
<Button
android:id="@+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:onClick="send"
android:text="Send"
tools:layout_editor_absoluteX="148dp"
tools:layout_editor_absoluteY="266dp" />
я хочу, чтобы идентификатор токена и идентификатор андроида отправлялись в API REST Azure.