将 curl 调用转换为 java urlconnection 调用

时间:2023-02-20
本文介绍了将 curl 调用转换为 java urlconnection 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有 curl 命令:

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":"#"}'

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

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

整个代码

推荐答案

这是最终解决方案:

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

  }

}

这篇关于将 curl 调用转换为 java urlconnection 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:spring boot rabbitmq MappingJackson2MessageConverter 自定义对象转换 下一篇:如何优雅地停止使用@RabbitListener 消费消息

相关文章

最新文章