【问题标题】:How to use the following curl post command in java?如何在java中使用以下curl post命令?
【发布时间】:2017-06-24 02:26:48
【问题描述】:

我查看了堆栈溢出的不同线程并进行了一些研究,但在建立 http 连接后,我无法在 java 中运行此代码。 相同的命令在命令行中运行良好

curl -X POST --header "Content-Type: application/json" --header "Accept: */*" -d "data" "http://a url"

我需要一个用于上述 curl 命令的 java 代码,我还没有想出任何有价值的东西

【问题讨论】:

  • 线程不关心 curl post 方法的 java 代码
  • 那么,你发现了哪些话题?您使用的是什么 HTTP 库?
  • tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection background.. 获取请求上的 WriteStream 并使用写入器将 -d 数据从 curl 放入 Request.OutStream。设置标题(只是 Content-type 可能不需要 Accept 和 .. 应该很好
  • @VasylLyashkevych 是吗?您提到的线程与 curl 命令的 java 实现几乎没有任何关系

标签: java json curl


【解决方案1】:

对于仍在寻找的人

{String urly = "your url";
URL obj = new URL(urly);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

con.setRequestMethod("POST");
con.setRequestProperty("Content-Type","application/json");


con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(the data string);
wr.flush();
wr.close();

int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);

BufferedReader iny = new BufferedReader(
new InputStreamReader(con.getInputStream()));
  String output;
  StringBuffer response = new StringBuffer();

  while ((output = iny.readLine()) != null) {
   response.append(output);
  }
  iny.close();

  //printing result from response
  System.out.println(response.toString());
 }

【讨论】:

  • 如果有更多关于“wr.writeBytes(数据字符串);”的细节会更好
猜你喜欢
  • 2016-08-15
  • 2017-07-07
  • 1970-01-01
  • 1970-01-01
  • 2014-07-26
  • 2023-01-15
  • 2017-07-07
  • 1970-01-01
  • 2019-09-18
相关资源
最近更新 更多