[英]Convert curl HTTP request in java
I have this curl command: 我有这个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"'" } } }}'
where $OS_USERNAME etc must be set by me, and i've to convert it in java. $ OS_USERNAME等必须由我设置的地方,我必须将其转换为Java。 I don't know how is the most easy way to do this because i'm not practice in java http request.
我不知道最简单的方法是怎么做到的,因为我不在Java HTTP请求中练习。
I try to use a code like this: 我尝试使用这样的代码:
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());
but i always receive 401 error. 但我总是收到401错误。
I try another way like this: 我尝试这样的另一种方式:
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");
but also this doesn't work. 但这也不起作用。 It returns me this exception:
它返回此异常:
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.