Java中的HTTP POST请求

时间:2017-09-29 02:21:56

标签: java php http http-post http-post-vars

基本上我尝试做的是使用我创建的PHP页面连接到Pastebin API。好像参数没有输入。这是我的代码:

String urlParameters = "?api_dev_key=" + main.getKey() + "&api_user_name=" + username + "&api_user_password=" + password; URL url = new URL("http://pastebinclient.tk/server/login.php" + urlParameters);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Language", "en-US");
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html) Safari/537.36");

connection.setUseCaches(false);
connection.setDoOutput(true);

我使用相同参数的http://hurl.it并且工作正常。在我的页面上,它被设置为如果所有参数都没有被输入,那么它返回一条消息说明,以及发生了什么。很抱歉,我提出的问题已经得到解答,但答案没有帮助。

2 个答案:

答案 0 :(得分:0)

您实际上并未在POST请求的正文中提交参数。您将在代码中将它们作为查询参数提交。根据web服务的编写方式,它可能会也可能不会接受作为查询参数发送的params。看起来在这种情况下它没有。有关如何将params作为POST正文的一部分提交的示例,请参阅Java - sending HTTP parameters via POST method easily

答案 1 :(得分:0)

我建议在apache http api上构建http-request

private static final HttpRequest<?> HTTP_REQUEST = 
      HttpRequestBuilder.createPost("http://pastebinclient.tk/server/login.php")
           .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
           .addDefaultHeader("Content-Type", "application/x-www-form-urlencoded") // I think there is no need
           .addDefaultHeader("Content-Language", "en-US")
           .addDefaultHeader("Accept", "*/*")
           .addDefaultHeader("User-Agent", "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html) Safari/537.36")
           .build();

public void send(){
   ResponseHandler<?> handler = HTTP_REQUEST.executeWithQuery(urlParameters);
   int statusCode = handler.getStatucCode();
}