5

我有 curl 命令:

curl -i -u guest:guest -H "content-type:application/json"
-XPUT \ http://localhost:15672/api/traces/%2f/my-trace \
-d'{"format":"text","pattern":"#"}'

我想在 Java API 中创建 HTTP 请求,它会做同样的事情。这个 curl 命令可以在这个README中找到。它用于在 RabbitMQ 上开始记录日志。回应并不重要。

现在我创建了这样的东西(我删除了不太重要的行,即捕获异常等),但不幸的是它不起作用:

url = new URL("http://localhost:15672/api/traces/%2f/my-trace");
uc = url.openConnection();

uc.setRequestProperty("Content-Type", "application/json");
uc.setRequestProperty("format","json");
uc.setRequestProperty("pattern","#")
String userpass = "guest:guest";
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
uc.setRequestProperty ("Authorization", basicAuth);

整个代码

4

2 回答 2

11

这是最终解决方案:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.Proxy;
import java.net.InetSocketAddress;
import java.io.OutputStreamWriter;

public class Curl {

  public static void main(String[] args) {

    try {

    String url = "http://127.0.0.1:15672/api/traces/%2f/trololo";

    URL obj = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

    conn.setRequestProperty("Content-Type", "application/json");
    conn.setDoOutput(true);

    conn.setRequestMethod("PUT");

    String userpass = "user" + ":" + "pass";
    String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes("UTF-8"));
    conn.setRequestProperty ("Authorization", basicAuth);

    String data =  "{\"format\":\"json\",\"pattern\":\"#\"}";
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    out.write(data);
    out.close();

    new InputStreamReader(conn.getInputStream());   

    } catch (Exception e) {
    e.printStackTrace();
    }

  }

}
于 2013-04-02T10:35:14.853 回答
1

我可以看到两个问题:

  • 您没有设置请求方法,在您的 curl 示例中它是“PUT”
  • '-d' 数据应该是请求正文,而不是请求参数(即您应该将该字符串写入请求输出流)

此外,当您这样做时,userpass.getBytes()您将使用默认平台字符编码获取字节。这可能是也可能不是您想要的编码。最好使用显式字符编码(大概是服务器所期望的)。

于 2013-03-28T15:05:17.090 回答