I have one web API service written in .NET. The service reads token from Header and data with in body.
I am looking Android code that call this server (It should pass token string in header and Json data in body. Please share code.
try this AsyncTask class :
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;
}
}
this code sends a json object with TripId and "token" header to an API url make sure that the json names match the parameter and header name or else there will be an error
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.