将curl调用转换为java urlconnection调用
我有curl命令:
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请求,该操作将执行相同的操作。可以在本README中找到该curl命令。它用于开始在RabbitMQ上记录日志。回应并不重要。
现在,我创建了这样的内容(我删除了不太重要的行,例如捕获了异常等),但是不幸的是,它不起作用:
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调用 的全部内容, 来源链接: utcz.com/qa/408916.html