java - 将 Apache Http 转换为 OkHttp android?
问题描述
我需要转换这个 Apache http 代码:
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("https://fcm.googleapis.com/fcm/send");
post.setHeader("Content-type", "application/json");
post.setHeader("Authorization", "key=AIzaSyBSxxxxsXevRq0trDbA9mhnY_2jqMoeChA");
JSONObject message = new JSONObject();
message.put("to", "dBbB2BFT-VY:APA91bHrvgfXbZa-K5eg9vVdUkIsHbMxxxxxc8dBAvoH_3ZtaahVVeMXP7Bm0iera5s37ChHmAVh29P8aAVa8HF0I0goZKPYdGT6lNl4MXN0na7xbmvF25c4ZLl0JkCDm_saXb51Vrte");
message.put("priority", "high");
JSONObject notification = new JSONObject();
notification.put("title", "Java");
notification.put("body", "Notificação do Java");
message.put("notification", notification);
post.setEntity(new StringEntity(message.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
System.out.println(response);
System.out.println(message);
我需要使用它,但是使用 okHttp,有可能吗?
解决方案
尝试这个:
JSONObject message = new JSONObject();
message.put("to", "dBbB2BFT-VY:APA91bHrvgfXbZa-K5eg9vVdUkIsHbMxxxxxc8dBAvoH_3ZtaahVVeMXP7Bm0iera5s37ChHmAVh29P8aAVa8HF0I0goZKPYdGT6lNl4MXN0na7xbmvF25c4ZLl0JkCDm_saXb51Vrte");
message.put("priority", "high");
JSONObject notification = new JSONObject();
notification.put("title", "Java");
notification.put("body", "Notificação do Java");
message.put("notification", notification);
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(message.toString(), JSON);
Request request = new Request.Builder()
.url("https://fcm.googleapis.com/fcm/send")
.addHeader("Authorization", "key=AIzaSyBSxxxxsXevRq0trDbA9mhnY_2jqMoeChA")
.addHeader("Content-Type", "application/json; charset=utf-8")
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response);
System.out.println(message);
}
推荐阅读
- html - 当我的输入相同(“”)时,为什么有些字符串包含“”和一些“”?
- arrays - 如何比较两个不同的 API 请求以在 Reactjs 中获取和显示重复值?
- mysql - 在 MYSQL 存储过程中使用 CTE (WITH)
- reactjs - React Hook setState 在 prop 触发时传递,但实际上并没有改变状态
- regex - 使用 grep 从二进制文件中提取非常特定的字符串
- docker - Docker-compose 卷路径在编辑后不会改变
- elasticsearch - 订单出现在`should`上会影响查询结果吗?
- python - Python 无法访问我的多 GB 内存?
- swiftui - 如何知道在视图列表中按下了哪个按钮 - SwiftUI
- flutter - 运行“flutter pub get”时,包到底托管在哪里?