Java 使用 HttpURLConnection 提交 json POST 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21268600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:47:21  来源:igfitidea点击:

Using HttpURLConnection to submit a json POST request

javajsonscalacurlhttprequest

提问by Austin

I am trying to submit a json post request using HttpURLConnection in Scala. I followed along to two tutorials and produced this:

我正在尝试使用 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()
}

It responds with:

它回应:

Sent: '{"schedule":"R/2014-02-02T00:00:00Z/PT24H", "name":"Scala-Post-Test", "command":"which scalac", "epsilon":"PT15M", "owner":"[email protected]", "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

stemming from

源于

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

but if I rebuild it as a curlrequest, it works fine:

但如果我根据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":"[email protected]", "async":false}' http://localhost:4040/scheduler/iso8601

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

(which is what I expect)

(这是我所期望的)

Any insight to what is wrong? I'm trying to sniff the packets now to determine what is different.

对什么是错的任何见解?我现在试图嗅探数据包以确定有什么不同。

(Note: I had previously given up on sys.process._)

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

采纳答案by Brian Roach

The issue is here:

问题在这里:

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

You'll note your JSON is surrounded by single quotes. This makes it invalid.

您会注意到您的 JSON 被单引号包围。这使它无效。

Also worth noting is that while this code works, you are using a DataOutputStream.writeBytes()to output your data. This would be problematic if your string including anything but single-byte characters; it strips the high 8 bits off each char(Java uses 2-byte chars to hold UTF-16 codepoints).

另外值得注意的是,虽然此代码有效,但您正在使用 aDataOutputStream.writeBytes()来输出您的数据。如果您的字符串包含除单字节字符以外的任何内容,这将是有问题的;它每个去掉高 8 位char(Java 使用 2 字节字符来保存 UTF-16 代码点)。

It's better to use something more suited for Stringoutput. The same technique you use for input, for example:

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

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