如何在Java中执行以下curl命令 [英] How do i do the following curl command in Java

查看:3262
本文介绍了如何在Java中执行以下curl命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How would I implement the following curl command in Java URLConnection

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


推荐答案

使用 URLConnection ,它是 HttpURLConnection ,您可以轻松地做到。

Using the derived class of URLConnection which is HttpURLConnection you can easily do it.

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 \ -HX-Parse- -Id:\ -HX-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();

这篇关于如何在Java中执行以下curl命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆