簡體   English   中英

在Java中轉換curl HTTP請求

[英]Convert curl HTTP request in java

我有這個curl命令:

curl -v -s -X POST $OS_AUTH_URL/auth/tokens?nocatalog   -H "Content-Type: application/json"   -d '{ "auth": { "identity": { "methods": ["password"],"password": {"user": {"domain": {"name": "'"$OS_USER_DOMAIN_NAME"'"},"name": "'"$OS_USERNAME"'", "password": "'"$OS_PASSWORD"'"} } }, "scope": { "project": { "domain": { "name": "'"$OS_PROJECT_DOMAIN_NAME"'" }, "name":  "'"$OS_PROJECT_NAME"'" } } }}' 

$ OS_USERNAME等必須由我設置的地方,我必須將其轉換為Java。 我不知道最簡單的方法是怎么做到的,因為我不在Java HTTP請求中練習。

我嘗試使用這樣的代碼:

String url = "http://myurl";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("user","myuser");
    con.setRequestProperty("password", "mypassword");

    con.setDoOutput(true);

    int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);

BufferedReader in = new BufferedReader(
        new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();

//print result
    System.out.println(response.toString());

但我總是收到401錯誤。

我嘗試這樣的另一種方式:

HttpPost httpPost = new HttpPost("http://192.168.1.107:5000/v3/auth/tokens?nocatalog ");
    String json = "'{ \"auth\": { \"identity\": { \"methods\": [\"password\"],\"password\": {\"user\": {\"domain\": {\"name\": \"'\"Default\"'\"},\"name\": \"'\"admin\"'\", \"password\": \"'\"MYPASSWORD\"'\"} } }, \"scope\": { \"project\": { \"domain\": { \"name\": \"'\"default\"'\" }, \"name\":  \"'\"admin\"'\" } } }}'";
    StringEntity entity = new StringEntity(json);
    httpPost.setEntity(entity);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");

但這也不起作用。 它返回此異常:

Exception in thread "main" java.lang.IllegalArgumentException: Illegal character in query at index 50: http://192.168.1.107:5000/v3/auth/tokens?nocatalog 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM