versuchen, diese AsyncTask Klasse:..
public class GetEvents extends AsyncTask<Integer,Void,String> {
@Override
protected String doInBackground(Integer... TripId) {
return POSTJson(URLs.API_URL);
}
protected void onPostExecute(String result) {
//code after execution
}
protected void onPreExecute() {
super.onPreExecute();
}
public String POSTJson(String url) {
UserToken = "YourToken";
String json;
URL obj;
try {
obj = new URL(url);
HttpURLConnection con;
con = (HttpURLConnection) obj.openConnection();
json = DATAtoJSON(TripId).toString();
//Requset headers
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-type", "application/json");
con.setRequestProperty("Token", UserToken);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
//request parameters
wr.writeBytes(json);
wr.flush();
wr.close();
//receive data from request
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public JSONObject DATAtoJSON(int TripId) {
//API corresponding keys
String TripId_Key = History_Json_Attribute.TripId;
JSONObject jsonObject = new JSONObject();
try {
jsonObject.accumulate(TripId_Key,TripId);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
}
dieser Code sendet Ein JSON-Objekt mit TripId und "Token" -Header zu einer API-URL stellen Sie sicher, dass die JSON-Namen mit dem Parameter und Header-Namen übereinstimmen oder andernfalls wird ein Fehler