open falcon接口API和java代码用okhttp连接的问题

来源:互联网 发布:淘宝主账号不收取信息 编辑:程序博客网 时间:2024/06/14 07:40

解决办法参考链接:https://raw.githubusercontent.com/square/okhttp/master/samples/guide/src/main/java/okhttp3/guide/PostExample.java

1. 问题描述:

open falcon监控软件,提供了很多接口API,java代码直接通过http请求去调用。

java代码中,用http请求别的项目接口,我一般喜欢用okhttp这个jar包。

本次使用,出现调不通的现象,

linux端看到http请求的Content-Type为application/x-www-form-urlencoded,而java中明明配置请求的header为("Content-Type", "application/json"),

调用open falcon的API接口需要的是("Content-Type", "application/json")


2. 问题原因以及解决办法:

问题原因是post请求传输的格式有问题,

(1)之前用的是如下代码,一直400或401:

FormEncodingBuilder builder = new FormEncodingBuilder();   
            builder.add("start","1503644100");
            builder.add("end","1503647640");
            builder.add("queries","[{\"metric\": \"cpu.user\",\"aggregator\": \"avg\",\"tags\": {\"endpoint\": \"l_1_13\"}}]");

Request request = new Request.Builder().url(url)
                    .post(builder.build())
                    .header("Content-Type", "application/json")
                    .build();
(2)之后用的如下代码,成功了:

public static final MediaType JSON= MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

 static String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
     Response response = client.newCall(request).execute();
      return response.body().string();
  }

  public static void main(String[] args) throws IOException {
        //入参

         String json="{\"start_time\":1503644100,"
                + "\"end_time\":1503647640,"
                + "\"consol_fun\":\"AVERAGE\","
                + "\"hostnames\":[\"l_1_13\"],"
                + "\"counters\":[\"cpu.user\"]}";
          String response = post("http://10.10.1.1:8083/api/v1/graph/history/", json);  // 此处ip,是你自己部署open falcon的机器ip和端口以及你需要调用的API
          System.out.println(response);
  }


3. open falcon API接口:





原创粉丝点击