0

我使用 influxdb 0.9。在这个版本中,我可以像这样编写数据库

curl -XPOST 'http://localhost:8086/write?db=mydb' -d 'cpu,host=server01,region=uswest value=1.0'

现在我将它转换为java

URL url = new URL("http", "localhost", 8086, "/write?db=mydb");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
OutputStream wr = con.getOutputStream();
Stirng s = "cpu,host=server01,region=uswest value=51.0";
wr.write(s.getBytes(UTF_8));
wr.flush();
wr.close();

但它不起作用。“-d”是代表post参数吗?我如何用 Java 表达它?

4

3 回答 3

0

在这个例子中,curl标志应该是--data-binary, not -d,它可以有不同的编码。只要您的字符串没有被 Java 代码更改,它应该没问题。像 URL 编码这样的任何东西都会阻止线路协议插入工作。

于 2015-07-14T22:05:43.243 回答
0

您还需要获取 HTTP 响应。以下对我有用:

import java.net.*;
import java.io.*;
import java.util.*;

public class Client {
    private static HttpURLConnection client;

    public static void main(String[] args) {
        try {
            Random rn = new Random();
            URL input;
            while(true) {
                input = new URL("http", "localhost", 8086, "/write?db=mydb");
                client = (HttpURLConnection) input.openConnection();
                client.setRequestMethod("POST");
                client.setDoOutput(true);

                double thermals = rn.nextDouble();
                String s = "cpu_temperature value=" + thermals;

                try (OutputStreamWriter writer =
                        new OutputStreamWriter(client.getOutputStream())) {
                    writer.write(s);
                }

                BufferedReader in = new BufferedReader(new InputStreamReader(
                                            client.getInputStream()));
                String decodedString;
                while ((decodedString = in.readLine()) != null) {
                    System.out.println(decodedString);
                }
                in.close();

                System.out.println(s); // for debugging
                Thread.sleep(1000); // send data every 1 second
            }

        } catch(MalformedURLException error) {
            System.out.println("Malformed URL!");
        } catch(SocketTimeoutException error) {
            System.out.println("Socket Timeout Exception!");
        } catch (IOException error) {
            System.out.println("IOException!");
            System.out.println(error);
        } catch(InterruptedException e) {
            System.out.println("InterruptedException!");
        } finally {
            if(client != null) { // Make sure the connection is not null.
                client.disconnect();
            }
        }



    }
}
于 2016-10-05T21:39:21.330 回答
0

您的 SQL 查询需要更正。在“cpu,host=”中删除“,”它会起作用。

于 2019-05-14T18:04:31.927 回答