2

我有 java 客户端,可以访问我创建的 API,但是当我运行基本上是 java 客户端的类时,它会抛出异常。这是例外。

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

这是代码:

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

     }

    }

}

我正在本地主机上对其进行测试,我也尝试用我的 IP 地址代替 localhost,但它不起作用,它也会抛出相同的异常。

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

提前致谢。

4

1 回答 1

3

您尝试访问的资源不存在,或不允许POST。你可以试试看有GET没有。如果不是,它应该返回一个404.

405返回码的意思是“不允许的方法”,在某些情况下,当资源完全丢失时可以看到。404意思是“未找到”。

于 2016-02-16T07:11:33.590 回答