convert curl call into java urlconnection call

前端 未结 2 382
-上瘾入骨i
-上瘾入骨i 2020-12-15 01:45

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\":\         


        
相关标签:
2条回答
  • 2020-12-15 02:00

    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();
        }
    
      }
    
    }
    
    0 讨论(0)
  • 2020-12-15 02:17

    two problems that i can see:

    • you aren't setting the request method, in your curl example it is "PUT"
    • the '-d' data should be the request body, not request parameters (i.e. you should be writing that string to the request OutputStream)

    also, when you do userpass.getBytes() you are getting the bytes using the default platform character encoding. this may or may not be the encoding that you desire. better to use an explicit character encoding (presumably the one the server is expecting).

    0 讨论(0)
提交回复
热议问题