将JSON请求发送到hipchat

时间:2014-06-07 18:39:25

标签: java json

我正在为我的HipChat房间制作一些东西,但为了工作,我必须发送一个JSON请求:

POST /v1/rooms/message?format=json&auth_token=token HTTP/1.1
Host: api.hipchat.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 138

room_id=10&from=Alerts&message=A+new+user+signed+up

到目前为止我有这个:

public static void send(String send){
    URL url = null;
    HttpURLConnection conn = null;

  try{
      url = new URL("http://api.hipchat.com");
      conn = (HttpURLConnection)url.openConnection();
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      conn.setRequestProperty("Content-Length", "138");

      conn.setUseCaches (false);
      conn.setDoInput(true);
      conn.setDoOutput(true);

      DataOutputStream wr = new DataOutputStream(
              conn.getOutputStream ());
      wr.writeBytes (send);
      wr.flush ();
      wr.close ();


      InputStream is = conn.getInputStream();
      BufferedReader rd = new BufferedReader(new InputStreamReader(is));
      String line;
      StringBuffer response = new StringBuffer();
      while((line = rd.readLine()) != null) {
          response.append(line);
          response.append('\r');
      }
      rd.close();
      System.out.println(line);
  }catch(Exception e){
    e.printStackTrace();
  }finally{
      if(conn != null) {
          conn.disconnect();
      }
  }
}

但是在控制台中它只返回null。我将如何发送上述JSON请求?

由于

1 个答案:

答案 0 :(得分:0)

每次你在这里循环

while((line = rd.readLine()) != null) {

您的line变量将替换为rd.readLine()返回的值。它最后一次循环,该方法调用将返回null。这就是为什么linenull

我假设您要打印response