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

3
  • 1
    where is curl command ? Commented Mar 17, 2015 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}' \ Commented Mar 17, 2015 at 22:14
  • You can use http client api and setHeader() method to set these headers Commented Mar 17, 2015 at 22:16

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the reply I get the following Server returned HTTP response code: 400 for URL: api.parse.com/1/classes/score
@user3130151 my bad it's because i've put single quote instead of double. Tell me if it works now ?
@user3130151 just updated it again using JSONObjet and URLEncoder you will most likely not have 400 response code this time :-)
Khaled this is amazing :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.