Vertx POST不起作用 - >错误404

时间:2016-10-04 08:12:16

标签: java azure post http-post vert.x

我不知道为什么,但我用Vertx做的帖子根本就不起作用。始终错误是404.
与纯Java一样使用的链接和主体,我从服务器得到了响应。我做错了什么?

HttpClient client = vertx.createHttpClient();

HttpClientRequest request = 
client.post("https://login.windows.net/common/oauth2/token").handler(res->{
                System.out.println(res.statusCode());
            }).putHeader(HttpHeaders.CONTENT_LENGTH,String.valueOf(buffer.length()))
.putHeader(HttpHeaders.CONTENT_TYPE,"application/x-www-form-urlencoded").write(buffer);
            request.end(); 

我基本上是在使用Azure进行身份验证,对于响应,我应该获得带有令牌和其他信息的JSON。使用纯Java,可以工作,但我们需要使它与Vertx一起使用。

编辑 - 此代码有效 - 我收回JSON,但不是vertx

String url = "https://login.microsoftonline.com/common/oauth2/token";
URL obj = null;
obj = new URL(url);
HttpsURLConnection con = null;
con = (HttpsURLConnection) obj.openConnection();

//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Host", "login.microsoftonline.com");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

// Send post request
con.setDoOutput(true);
DataOutputStream wr = null;

wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

int responseCode = 0;
responseCode = con.getResponseCode();

System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);

BufferedReader in = null;
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());

1 个答案:

答案 0 :(得分:1)

似乎问题是由于在没有启用SSL的情况下请求HTTPS网址并指定443端口引起的。 Vert.x httpclient默认支持访问Web主机端口80的HTTP请求。您需要通过HttpClientOptions为httpclient启用SSL支持。

请尝试使用以下代码而不是您的代码。

HttpClient client = vertx.createHttpClient(new HttpClientOptions().setSsl(true).setTrustAll(true));
HttpClientRequest request = client.post(443, "login.windows.net", "/common/oauth2/token").handler(res->{
                System.out.println(res.statusCode());
     }).putHeader(HttpHeaders.CONTENT_LENGTH,String.valueOf(buffer.length()))
.putHeader(HttpHeaders.CONTENT_TYPE,"application/x-www-form-urlencoded").write(buffer);
request.end(); 

作为参考,请查看官方文档http://vertx.io/docs/vertx-core/java/#_using_https_with_vert_x和GitHub https://github.com/vert-x3/vertx-examples/blob/master/core-examples/src/main/java/io/vertx/example/core/http/https/Client.java中的代码示例。