我有 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 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
解析 ISO 8601 字符串本地日期时间,就像在 UTC 中Parsing an ISO 8601 string local date-time as if in UTC(解析 ISO 8601 字符串本地日期时间,就像在 UTC 中一样)
如何将公历字符串转换为公历?How to convert Gregorian string to Gregorian Calendar?(如何将公历字符串转换为公历?)
Java:GregorianCalendar 的最大值和最小值是什么/在哪Java: What/where are the maximum and minimum values of a GregorianCalendar?(Java:GregorianCalendar 的最大值和最小值是什么/在哪里?)
1582 年 10 月 15 日之前日期的日历到日期转换.公历Calendar to Date conversion for dates before 15 Oct 1582. Gregorian to Julian calendar switch(1582 年 10 月 15 日之前日期的日历到日期转换
java日历setFirstDayOfWeek不起作用java Calendar setFirstDayOfWeek not working(java日历setFirstDayOfWeek不起作用)
Java:获取当前星期几的值Java: getting current Day of the Week value(Java:获取当前星期几的值)