How to send JSON data to the server using the POST method using authorizations in the Authorization header

Example of JSON data sent to the server:

Header: Authorization Bearer UXFTltj-kISwxisaawt2elpDbkvy

{ "status": "active", "error": "No error", "type": "sms", "data": { "id": 5, "name": "Кукуруза на Марсе", "params": { "1": "Возможно", "2": "Невозможно", "3": "Бред", "4": "А где это?", "6": "А что это?" } }} 
  • Maybe OkHttp is suitable - diraria
  • one
    I just started to study, if it’s not difficult for you to describe the solution in more detail, and even better to give the source code for study. - dev.android

1 answer 1

You can use OkHttp . Here is a copy of the example from here , with the addition of one line responsible for the authorization header. In this example, we define a post function that accepts two lines — url (the address where we send the request) and json (a line with a json object).

 public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); String post(String url, String json) throws IOException { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) // эта строчка была добавлена .header("Authorization", "Bearer UXFTltj-kISwxisaawt2elpDbkvy") // ============ .post(body) .build(); Response response = client.newCall(request).execute(); return response.body().string(); } 
  • one
    Thank you very much! - dev.android