3

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}'

Thanks in advance

BentoumiTech
  • 1,627
  • 14
  • 21
user3130151
  • 115
  • 3
  • 6
  • 1
    where is curl command ? – jmj Mar 17 '15 at 22:11
  • curl -X PUT \ -H "X-Parse-Application-Id: " \ -H "X-Parse-REST-API-Key: " \ -H "Content-Type: application/json" \ -d '{"score":73453}' \ – user3130151 Mar 17 '15 at 22:14
  • You can use http client api and [`setHeader()`](http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/message/AbstractHttpMessage.html?is-external=true#setHeader%28org.apache.http.Header%29) method to set these headers – jmj Mar 17 '15 at 22:16

1 Answers1

6

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();

For 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();
BentoumiTech
  • 1,627
  • 14
  • 21