本文介紹了將 curl 調(diào)用轉(zhuǎn)換為 java urlconnection 調(diào)用的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
限時(shí)送ChatGPT賬號(hào)..
我有 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 中創(chuàng)建 HTTP 請(qǐng)求,它會(huì)做同樣的事情.這個(gè) curl 命令可以在這個(gè) README 中找到.它用于在 RabbitMQ 上開(kāi)始記錄日志.回應(yīng)并不重要.
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.
現(xiàn)在我創(chuàng)建了這樣的東西(我已經(jīng)刪除了不太重要的行,即捕獲異常等),但不幸的是它不起作用:
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);
整個(gè)代碼
推薦答案
這是最終解決方案:
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();
}
}
}
這篇關(guān)于將 curl 調(diào)用轉(zhuǎn)換為 java urlconnection 調(diào)用的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!