【问题标题】:How do i do the following curl command in Java我如何在 Java 中执行以下 curl 命令
【发布时间】:2015-03-17 22:11:24
【问题描述】:

我将如何在 Java URLConnection 中实现以下 curl 命令

curl -X PUT \
  -H "X-Parse-Application-Id: " \
  -H "X-Parse-REST-API-Key: " \
  -H "Content-Type: application/json" \
  -d '{"score":73453}'

提前致谢

【问题讨论】:

  • curl 命令在哪里?
  • curl -X PUT \ -H "X-Parse-Application-Id: " \ -H "X-Parse-REST-API-Key: " \ -H "Content-Type: application/ json" \ -d '{"score":73453}' \
  • 你可以使用http客户端api和setHeader()方法来设置这些headers

标签: java url curl urlconnection


【解决方案1】:

使用URLConnection 的派生类HttpURLConnection 可以轻松做到。

URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
myURLConnection.setRequestMethod("PUT");
myURLConnection.setRequestProperty("X-Parse-Application-Id", "");
myURLConnection.setRequestProperty("X-Parse-REST-API-Key", "");
myURLConnection.setRequestProperty("Content-Type", "application/json");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
myURLConnection.connect();

JSONObject jsonParam = new JSONObject();
jsonParam.put("score", "73453");

OutputStream os = myURLConnection.getOutputStream();
os.write(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
os.close();

对于curl -X GET \ -H "X-Parse-Application-Id: " \ -H "X-Parse-REST-API-Key: " \ -G \ --data-urlencode 'include=game

String charset = "UTF-8";
String query = String.format("include=%s", URLEncoder.encode("game", charset));
URL myURL = new URL(serviceURL+"?"+query);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
myURLConnection.setRequestMethod("GET");
myURLConnection.setRequestProperty("X-Parse-Application-Id", "");
myURLConnection.setRequestProperty("X-Parse-REST-API-Key", "");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
myURLConnection.connect();

【讨论】:

  • 感谢您的回复,我收到以下服务器返回的 HTTP 响应代码:400 for URL:api.parse.com/1/classes/score
  • @user3130151 我的错是因为我放了单引号而不是双引号。告诉我它现在是否有效?
  • @user3130151 刚刚使用 JSONObjet 和 URLEncoder 再次更新了它,这次你很可能没有 400 响应代码 :-)
  • Khaled 这太棒了:D
猜你喜欢
  • 2016-08-15
  • 1970-01-01
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 2018-10-04
  • 2016-01-05
  • 1970-01-01
相关资源
最近更新 更多