convert curl call into java urlconnection call(将 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 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 curl 调用转换为 java urlconnection 调用
基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01