使用HttpURLConnection提交json POST请求

时间:2014-01-21 20:37:05

标签: java json scala curl httprequest

我正在尝试使用Scala中的HttpURLConnection提交json post请求。我接着讲了两个教程并制作了这个:

def sendPost(url: String, jsonHash: String) {
  val conn: HttpURLConnection = new URL(url).openConnection().asInstanceOf[HttpURLConnection]
  conn.setRequestMethod("POST")
  conn.setRequestProperty("Content-Type", "application/json")
  conn.setRequestProperty("Accept", "application/json")
  conn.setDoOutput(true)
  conn.connect()

  val wr = new DataOutputStream(conn.getOutputStream)
  wr.writeBytes(jsonHash)
  wr.flush()
  wr.close()

  val responseCode = conn.getResponseCode

  println("Sent: " + jsonHash + " to " + url + " received " + responseCode)

  val in = new BufferedReader(new InputStreamReader(conn.getInputStream))
  var response: String = ""
  while(response != null) {
    response = in.readLine()
    println(response)
  }
  in.close()
}

它回应:

Sent: '{"schedule":"R/2014-02-02T00:00:00Z/PT24H", "name":"Scala-Post-Test", "command":"which scalac", "epsilon":"PT15M", "owner":"myemail@thecompany.com", "async":false}' to http://localhost:4040/scheduler/iso8601 received 500 

java.io.IOException: Server returned HTTP response code: 500 for URL: http://localhost:4040/scheduler/iso8601

源于

val in = new BufferedReader(new InputStreamReader(conn.getInputStream))

但如果我将其重建为curl请求,则可以正常工作:

curl -X POST -H 'Content-Type: application/json' -d '{"schedule":"R/2014-02-02T00:00:00Z/PT24H", "name":"Scala-Post-Test", "command":"which scalac", "epsilon":"PT15M", "owner":"myemail@thecompany.com", "async":false}' http://localhost:4040/scheduler/iso8601

requirement failed: Vertex already exists in graph Scala-Post-Test

(这是我的期望)

任何有关错误的见解?我现在正试图嗅探数据包以确定不同之处。

(注意:我之前放弃了sys.process._

1 个答案:

答案 0 :(得分:4)

问题在于:

Sent: '{"schedule":"R/2014-02-02T00:00:00Z/PT24H", "name":"Scala-Post-Test", "command":"which scalac", "epsilon":"PT15M", "owner":"myemail@thecompany.com", "async":false}' to http://localhost:4040/scheduler/iso8601 received 500

您会注意到您的JSON被单引号括起来。这使它无效。

另外值得注意的是,虽然此代码正常工作,但您使用DataOutputStream.writeBytes()输出数据。如果您的字符串包含除单字节字符之外的任何内容,则会出现问题;它从每个char剥离高8位(Java使用2字节字符来保存UTF-16代码点)。

最好使用更适合String输出的内容。您用于输入的相同技术,例如:

BufferedWriter out = 
    new BufferedWriter(new OutputStreamWriter(conn.getOutputStream));
out.write(jsonString);
out.close();