我想将json对象{“PersonID”:“124”,“DeviceID”:“123”,“ExpID”:“1234”,“ID”:“4566”}发送到特定的Azure Rest API URL
Ive尝试使用下面的代码它适用于URL-http://hmkcode.appspot.com/jsonservlet,但不适用于我的AZURE REST API的URL
main activity.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" />
我想将Token id,android id发送到Azure REST API。
我想帮助您,但我需要您提供更多信息。例如,您的代码段是否会抛出任何错误? conn.getRepsonseMessage()
回归了什么?此外,您表示您正在对该网址发帖。点击链接我确实得到了JSON,但当我尝试进行POST时出现500错误,这让我相信端点只接受GET。
我将遵循的步骤是使用像fiddler这样的工具对您的Azure API端点进行POST,并确保在您获得200秒后,该方面没有错误。