Java使用拦截器发送http帖子

时间:2019-01-29 06:43:34

标签: java http post

我想发送带有拦截器的http帖子,包括标题(cookies ... etc)和主体。我用post man测试它正常(需要启用chrome中的拦截器添加)。如何发送带有Java代码的http帖子。请帮助我。enter image description here

1 个答案:

答案 0 :(得分:0)

如果要将POST请求发送到URL,则只需一个HTTP库。常见的是OkHttp。直接来自他们的site的示例:

public static final MediaType JSON
    = MediaType.get("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)
      .post(body)
      .build();
  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}