小编典典

我如何在Java中执行以下curl命令

java

我如何在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}'

提前致谢


阅读 307

收藏
2020-11-26

共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();
2020-11-26