Java HTTP后辅助

时间:2016-03-21 21:23:16

标签: java http slack

我一直在使用Java中的Slack API,并且一直在尝试获取一个可以像下面的示例代码块一样使用的HTTP方法。该代码块有效,但问题是我还需要包含200响应代码,并且无法弄清楚如何使其工作。

基本上,我如何在Java中发送HTTP帖子,并使用URL和内容标记200状态代码?

当前代码:

public void httpRequest(URL url, String content) {
 try {
  byte[] contentBytes = content.getBytes("UTF-8");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setDoInput(true);
  connection.setDoOutput(true);
  connection.setRequestProperty("Accept-Charset", "UTF-8");
  connection.setRequestProperty("Content-Type", "application/json");
  connection.setRequestProperty("Content-Length", Integer.toString(contentBytes.length));
  connection.setRequestProperty("Status", Integer.toString(200));

  OutputStream requestStream = connection.getOutputStream();
  requestStream.write(contentBytes, 0, contentBytes.length);
  requestStream.close();

  String response = "";
  BufferedReader responseStream;
  response = "" + ((HttpURLConnection) connection).getResponseCode();
  try {
   if (((HttpURLConnection) connection).getResponseCode() == 200) {
    responseStream = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
   } else {
    responseStream = new BufferedReader(new InputStreamReader(((HttpURLConnection) connection).getErrorStream(), "UTF-8"));
   }
   response = responseStream.readLine();
   responseStream.close();
  } catch (NullPointerException ignored) {

  }
 } catch (IOException e) {
  e.printStackTrace();
 }
}

1 个答案:

答案 0 :(得分:0)

setDoOutput(true)的调用会触发帖子,即您无需添加

connection.setRequestMethod("POST");

正如您所做的那样,可以向请求添加状态标头,但通常会将状态代码与http 响应相关联,而非请求。 - 当然,添加这样的自定义标题只有在服务器被设计为将此信息用于任何事情时才有意义。

在java.net.HttpURLConnection上查看this个大而且高度投票的答案。

此外,您的响应变量以及BufferedReader也存在一些问题。您不小心覆盖了最初分配给响应字段的值,而不是连接。此外,您的 readLine()可能应该处于循环中:

String tmp;
while ((tmp = responseStream.readLine()) !=null){
      response += tmp;
}