【发布时间】:2015-04-25 05:00:28
【问题描述】:
能否请您帮我在 JAVA 中编写一个适当的 HTTP POST 请求,以使用他们的 REST API 在 YouTrack 中进行身份验证?它应该看起来像 like this(取自 YouTrack 文档):
POST http://localhost:8081/rest/user/login
Content-Length: 24
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Cookie:
login=root&password=root
我编写了以下代码来打开连接、发送 cookie 并处理服务器响应:
URL url = new URL(webPage);
URLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setDoOutput(true);
urlc.setDoInput(true);
((HttpURLConnection) urlc).setRequestMethod("POST");
urlc.setRequestProperty("Content-Length", Integer.toString(24));
urlc.setRequestProperty("Connection", "keep-alive");
urlc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String myCookie = "login=root&password=root";
urlc.setRequestProperty("Cookie", myCookie);
InputStream is = urlc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
String result = sb.toString();
System.out.println("result = " + result);
但是我收到了 HTTP 响应 400。 请告诉我我做错了什么?如果您建议对这个问题做出决定,我将不胜感激。谢谢!
【问题讨论】:
-
发送时是什么样子的?
-
我在控制台上收到以下文本:java.io.IOException:服务器返回 HTTP 响应代码:400 用于 URL:server_address/rest/user/login at sun.net.www.protocol。 http.HttpURLConnection.getInputStream0(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) atreporting.YouTrackApiActions$SSLTest.main(YouTrackApiActions.java:59)
-
使用任何可用的 API 测试工具(例如 RESTClient、POSTMan 等)在浏览器中尝试相同的请求。您的代码看起来还可以。你可能不符合 api
-
java:59 是创建 InputStream 的字符串
-
谢谢你,kolossus,我去试试
标签: java rest post cookies youtrack