2

Добрые день. Формирую запрос в Firebase API через okhttp либу кодом:

JSONObject data = new JSONObject();
    data.put("event", "goChat");

    String[] registration_ids = {"client token firebase"};
    JSONObject protocol = new JSONObject();
    protocol.put("registration_ids", registration_ids); //
    protocol.put("data", data);

    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    RequestBody body = RequestBody.create(JSON, protocol.toString());

    Request request = new Request.Builder()
            .url(urlFirebaseApi)
            .addHeader("Content-type", "application/json")
            .addHeader("Authorization:key=", MY_APP_FB_KEY)
            .post(body)
            .build();

     Response response = client.newCall(request).execute();

Получаю пост запрос вида(ловлю его модулем Apache на тестовом сервере):

    --0e16940d-A--
[26/Feb/2018:19:39:32 +0600] WpQOFH8AAQEAAGkSlzcAAAAB 192.168.1.2 55161 192.168.1.30 80
--0e16940d-B--
POST / HTTP/1.1
content-type: application/json
Authorization: key=: AAAAzX_mvfQ:APA91bE1Y-1ao......... MY APP FB KEY
Content-Length: 306
Host: 192.168.1.30
Connection: Keep-Alive
Accept-Encoding: gzip
User-Agent: okhttp/3.10.0

--0e16940d-C--
{"data":{"event":"goChat"}, "registration_ids":["client token FB there"]}
--0e16940d-F--
HTTP/1.1 404 Not Found
Content-Length: 276
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1
--0e16940d-E--

И https://fcm.googleapis.com/fcm/send отвечает code=400, что говорит об ошибке парсинга данных json. Ладно думаю я. Делаю скрипт на пхп, пробую отправить запрос на Api с помощью CURL. Код PHP:

$fields = array (
    'registration_ids' => array (
        "MY_TOKEN_DB"
    ),
    'data' => array (
        "event" => $event,
    )
);
$fields = json_encode ( $fields );

$headers = array (
    'Authorization: key=' . "MY_APP_FB_KEY",
    'Content-Type: application/json'
);

$myCurl = curl_init ();
curl_setopt ( $myCurl, CURLOPT_URL, $url );
curl_setopt ( $myCurl, CURLOPT_POST, true );
curl_setopt ( $myCurl, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $myCurl, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $myCurl, CURLOPT_POSTFIELDS, $fields );

$result = curl_exec ( $myCurl );
curl_close ( $myCurl );

Тело запроса, также отловленное с помощью мода апача:

[26/Feb/2018:19:35:09 +0600] WpQNDX8AAQEAAGkUxeAAAAAD 192.168.1.30 51266 192.168.1.30 80
--29939b3b-B--
POST / HTTP/1.1
Host: 192.168.1.30
Accept: */*
Authorization: key=MY_APP_KEY_FB
Content-Type: application/json
Content-Length: 362

--29939b3b-C--
{"registration_ids":["CLIENT_TOKEN_FB"],
"data":{"event":"goChat"}}
--29939b3b-F--
HTTP/1.1 404 Not Found
Content-Length: 276
Content-Type: text/html; charset=iso-8859-1

И все срабатывает! Бьюсь уже три часа и не пойму. В POST запросах понимаю слабо, надеюсь кто-то пояснит, благодарен заранеею

2 ответа 2

2

Вы неверно указываете заголовок для запроса. Имя заголовка идёт до двоеточия, значение - после. Т.е. должно быть так:

.addHeader("Authorization", "key=" + MY_APP_FB_KEY)
1
  • Спасибо, действительно, все заработало. А хотя все равно response говорит что ошибка парсинга, но все работает.
    – Gloster
    26 фев 2018 в 16:22
1

Если httpok не принципиально, то попробуй RestAssured, вот так примерно должно работать

import static com.jayway.restassured.RestAssured.config;
import static com.jayway.restassured.RestAssured.given;

    String[] registration_ids = {"client token firebase"};
    String url = "https://";
    Response response = given()
            .headers("Content-Type", "application/json")
            .headers("Authorization:key=", MY_APP_FB_KEY)
            .when()
            .body(new JSONObject().put("registration_ids", registration_ids)
                    .put("data", new JSONObject().put("event", "goChat").toString()).toString())
            .post(url);

или так мб проще:

import static com.jayway.restassured.RestAssured.config;
import static com.jayway.restassured.RestAssured.given;
        String[] registration_ids = {"client token firebase"};
        String url = "https://";

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("registration_ids", registration_ids);
    jsonObject.put("data", new JSONObject().put("event", "goChat").toString());


    Response response = given()
            .headers("Content-Type", "application/json")
            .headers("Authorization:key=", MY_APP_FB_KEY)
            .when()
            .body(jsonObject.toString())
            .post(url);

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.