1

I want to send this request through my java code:

curl -u "user:key" -X PUT -H "Content-Type: application/json" -d "{"status":"test", "reason":"test"}" https://test.com/test/id.json

I've tried using Runtime:

String command =
        "curl -u \"" + user + ":" + key + "\" -X PUT -H \"Content-Type: application/json\" -d \""
                + "{\\\"status\\\":\\\"test\\\","
                        + "\\\"reason\\\":\\\"test\\\"}\" "
                                + urlString + jsonID + ".json";

Runtime.getRuntime().exec(command); 

I've also tried ProcessBuilder:

String[] command2 = {"curl", "-u", "\"" + user + ":" + key + "\"", "-X", "PUT", "-H", "\"Content-Type: application/json\"", "-d",
                "\"{\\\"status\\\":\\\"test\\\",\\\"reason\\\":\\\"test\\\"}\"", 
                urlString + jsonID + ".json"};

Process proc = new ProcessBuilder(command2).start();

And finally with Apache HttpClient

        credsProvider.setCredentials(new AuthScope("test.com", 80), new UsernamePasswordCredentials(user, key));
        HttpClientBuilder clientbuilder = HttpClients.custom();
        clientbuilder = clientbuilder.setDefaultCredentialsProvider(credsProvider);
        CloseableHttpClient httpClient = clientbuilder.build();

        HttpPut put = new HttpPut(urlString + jsonID + ".json");

        put.setHeader("Content-type", "application/json");

        String inputJson = "{\n" +
                "  \"status\": \"test\",\n" +
                "  \"reason\": \"test\"\n" +
                "}";

        try {
            StringEntity stringEntity = new StringEntity(inputJson);
            put.setEntity(stringEntity);

            System.out.println("Executing request " + put.getRequestLine());

            HttpResponse response = null;
            response = httpClient.execute(put);
            BufferedReader br = new BufferedReader(
                    new InputStreamReader((response.getEntity().getContent())));
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + response.getStatusLine().getStatusCode());
            }
            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = br.readLine()) != null) {
                System.out.println("Response : \n"+result.append(line));
            }
        } catch (UnsupportedEncodingException e1) {

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

The Runtime and ProcessBuilders didn't return any results, but Apache HttpClient returned an Error 401 even though my credentials are correct. If I were to copy the command string and enter it into terminal, it would give a valid response.

Any help please? I've been on this for hours :(

1 Answer 1

1

Finally got it working

            String host = //use your same url but replace the https:// with www
            String uriString = String.format("https://%s:%s@%s%s.json", user, key, host, jsonID);
            Log.debug("Sending PUT request to URI: {}\n\n", uriString);

            try {
                URI uri = new URI(uriString);
                HttpPut putRequest = new HttpPut(uri);
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add((new BasicNameValuePair("status", status)));
                nameValuePairs.add((new BasicNameValuePair("reason", "TEST " + status.toUpperCase())));
                putRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = HttpClientBuilder.create().build().execute(putRequest);

                System.out.println("\n");
                Log.debug("Retrieving API response");
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));
                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new RuntimeException("Failed : HTTP error code : "
                            + response.getStatusLine().getStatusCode());
                }
                StringBuffer result = new StringBuffer();
                String line = "";
                while ((line = br.readLine()) != null) {
                    Log.debug("Response : \n{}", result.append(line));
                }

            } 

Hope this helps anyone looking for a similar solution in the future. Again this is for a curl request that looks like this: curl -u "user:key" -X PUT -H "Content-Type: application/json" -d "{"key":"value", "key2":"value2"}" https://test.com/test/id.json

Sign up to request clarification or add additional context in comments.

Comments

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.