Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have curl command:

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

And I want to create HTTP Request in Java API which will do the same thing. This curl command can be found in this README. It is used to start recording log on RabbitMQ. Response is not important.

For now I created something like this (I've deleted less important lines i.e. with catching exception etc.), but unfortunately it doesn't work:

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

This is final solution:

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

  }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...