Java REST API

I have a java client that processes the API that I created, but when I run the class, which is basically a java client, then it throws an exception. Here is the exception.

Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 405
    at TST.main(TST.java:29)

Here is the code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class TST {

    // http://localhost:8080/RESTfulExample/json/product/post
    public static void main(String[] args) {

      try {

        URL url = new URL("http://localhost:8080/JAXRS-FileUpload/rest/files/upload");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "text/plain");

        String input = "/home/hassan/Downloads/56963a249bff5_4__67_green-lantern_issue70.png";

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

      } catch (MalformedURLException e) {

        e.printStackTrace();

      } catch (IOException e) {

        e.printStackTrace();

     }

    }

}

I am testing it on a local host, I also tried to write my IP address instead of localhost, but it did not work, it also throws the same exception.

URL url = new URL (" http://192.168.1.3:8080/JAXRS-FileUpload/rest/files/upload ");

Thanks in advance.

+4
source share
1 answer

, , POST. GET , . , 404.

405 " ", , . 404 " ".

+3

Source: https://habr.com/ru/post/1628932/


All Articles