Как запустить команду curl с параметром -u и данными json в Java? - PullRequest
0 голосов
/ 30 апреля 2020

Я хочу отправить этот запрос через мой java код:

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

Я пытался использовать 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); 

Я также пытался 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();

И, наконец, с 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();
        }

Runtime и ProcessBuilders не дали никаких результатов, но Apache HttpClient вернул ошибку 401, даже если мои учетные данные верны. Если бы я скопировал строку command и ввел ее в терминал, это дало бы верный ответ.

Любая помощь, пожалуйста? Я занимаюсь этим часами: (

1 Ответ

0 голосов
/ 02 мая 2020

Наконец-то все заработало

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

            } 

Надеюсь, это поможет любому, кто ищет подобное решение в будущем. Опять же, это для запроса curl, который выглядит следующим образом: curl -u "user:key" -X PUT -H "Content-Type: application/json" -d "{"key":"value", "key2":"value2"}" https://test.com/test/id.json

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...