繁体   English   中英

在请求 OkHttp 中发送 JSON

[英]Send JSON in request OkHttp

朋友们!

我有一个简单的 HTTP 请求:

void postRequest(String postUrl,String phone, String message) throws IOException {

    OkHttpClient client = new OkHttpClient();

    //RequestBody body = RequestBody.create(JSON, postBody);
    RequestBody body = new FormBody.Builder()
            .add("phone", phone)
            .add("message", message)
            .build();

    Request request = new Request.Builder()
            .url(postUrl)
            .post(body)
            .build();
    //System.out.println(request);

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            call.cancel();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.d("TAG",response.body().string());
        }
    });
}

如何正确实现发送 JSON object 而不是简单的参数? 我的尝试没有成功,所以我真的需要一个提示。

将接受 JSON 的服务器正在 AKKA-HTTP 上运行。 如何正确向该服务器发送请求?

final case class Message(phone: String, message: String, service: String)
  implicit val item = jsonFormat3(Message)
  val queue: Queue[Message] = Queue()

val addMessage = post {
      path("add_message"){
        parameters("phone".as[String], "message".as[String], "service".as[String]){
          (phone, message, service) => {
            queue.enqueue(Message(phone, message, service))
            complete("ok")
          }
        }
      }
    }

map 并以 JSON 格式序列化 object 的最简单方法是使用ObjectMapper ZA2F2ED4F8EBC2CBBD4ZC21 的 ObjectMapper ZA2F2ED4F8EBC2CBBD4ZC2A库。

我个人用它来实现RestController的集成测试,效果很好。 这是我实现的实用程序 class,您可以将其用于您的目的:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public final class JsonUtils {

    public static String json(Object obj) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(obj);
    }
}

What you need to have is a POJO class which implements Serializable , and then pass the instance of your class to the json method and it will return the JSON format.

您绝对可以将它用于 Android 项目。 我发现了许多可以添加依赖项的示例,但这取决于您使用的是 Gradle 还是 Maven。

试试看!!!

你觉得这个选项怎么样? 我试图实现它,但发送失败。 我错过了一个重要的细节。 但我不明白它是什么。

// create your json here
JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("KEY1", "VALUE1");
    jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
    e.printStackTrace();
}

  OkHttpClient client = new OkHttpClient();
  MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  // put your json here
  RequestBody body = RequestBody.create(JSON, jsonObject.toString());
  Request request = new Request.Builder()
                    .url("https://YOUR_URL/")
                    .post(body)
                    .build();

  Response response = null;
  try {
      response = client.newCall(request).execute();
      String resStr = response.body().string();
  } catch (IOException e) {
      e.printStackTrace();
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM