将curl调用转换为java urlconnection调用

时间:2013-03-28 14:46:21

标签: java curl rabbitmq tracing

我有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请求,它将执行相同的操作。可以在此README中找到此curl命令。它用于开始在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);

ENTIRE CODE

2 个答案:

答案 0 :(得分:9)

这是最终解决方案:

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();
    }

  }

}

答案 1 :(得分:1)

我可以看到两个问题:

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

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