【问题标题】:Why got 405 error when post data to website by using Java?为什么使用 Java 将数据发布到网站时会出现 405 错误?
【发布时间】:2012-05-15 15:22:03
【问题描述】:

我只是尝试使用以下代码将数据发布到谷歌,但总是出现 405 错误,谁能告诉我方法?

package com.tom.labs;
import java.net.*;
import java.io.*;
public class JavaHttp {
    public static void main(String[] args) throws Exception {
        File data = new File("D:\\in.txt");
        File result = new File("D:\\out.txt");
        FileOutputStream out = new FileOutputStream(result);
        OutputStreamWriter writer = new OutputStreamWriter(out); 
        Reader reader = new InputStreamReader(new FileInputStream(data));
        postData(reader,new URL("http://google.com"),writer);//Not working
        //postData(reader,new URL("http://google.com/search"),writer);//Not working
        sendGetRequest("http://google.com/search", "q=Hello");//Works properly
    }

    public static String sendGetRequest(String endpoint,
            String requestParameters) {
        String result = null;
        if (endpoint.startsWith("http://")) {
            // Send a GET request to the servlet
            try {
                // Send data
                String urlStr = endpoint;
                if (requestParameters != null && requestParameters.length() > 0) {
                    urlStr += "?" + requestParameters;
                }
                URL url = new URL(urlStr);
                URLConnection conn = url.openConnection();
                // Get the response
                BufferedReader rd = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = rd.readLine()) != null) {
                    sb.append(line);
                }
                rd.close();
                result = sb.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(result);
        return result;
    }

    /**
     * Reads data from the data reader and posts it to a server via POST
     * request. data - The data you want to send endpoint - The server's address
     * output - writes the server's response to output
     * 
     * @throws Exception
     */
    public static void postData(Reader data, URL endpoint, Writer output)
            throws Exception {
        HttpURLConnection urlc = null;
        try {
            urlc = (HttpURLConnection) endpoint.openConnection();
            try {
                urlc.setRequestMethod("POST");
            } catch (ProtocolException e) {
                throw new Exception(
                        "Shouldn't happen: HttpURLConnection doesn't support POST??",
                        e);
            }
            urlc.setDoOutput(true);
            urlc.setDoInput(true);
            urlc.setUseCaches(false);
            urlc.setAllowUserInteraction(false);
            urlc.setRequestProperty("Content-type", "text/xml; charset=UTF-8");
            OutputStream out = urlc.getOutputStream();
            try {
                Writer writer = new OutputStreamWriter(out, "UTF-8");
                pipe(data, writer);
                writer.close();
            } catch (IOException e) {
                throw new Exception("IOException while posting data", e);
            } finally {
                if (out != null)
                    out.close();
            }
            InputStream in = urlc.getInputStream();
            try {
                Reader reader = new InputStreamReader(in);
                pipe(reader, output);
                reader.close();
            } catch (IOException e) {
                throw new Exception("IOException while reading response", e);
            } finally {
                if (in != null)
                    in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("Connection error (is server running at "
                    + endpoint + " ?): " + e);
        } finally {
            if (urlc != null)
                urlc.disconnect();
        }
    }

    /**
     * Pipes everything from the reader to the writer via a buffer
     */
    private static void pipe(Reader reader, Writer writer) throws IOException {
        char[] buf = new char[1024];
        int read = 0;
        while ((read = reader.read(buf)) >= 0) {
            writer.write(buf, 0, read);
        }
        writer.flush();
    }
}

【问题讨论】:

  • 如果谷歌不为他们的项目提供方便的界面 - 这意味着他们不希望机器人与他们互动,我敢打赌这违反了他们的 TOS
  • PS:将所有自我描述和特定的例外转换为Excelption 绝不是一个好主意
  • 谢谢,你能告诉我你是怎么处理我的代码的吗?为什么我不能正确格式化它?
  • 如果您阅读有关格式化的文档,您可以对其进行格式化:stackoverflow.com/editing-help

标签: java http http-status-code-405


【解决方案1】:

405 表示“方法不允许”。例如,如果您尝试将 POST 发送到不允许 POST 的 URL,则服务器将返回 405 状态。

您想通过向 Google 发出 POST 请求来做什么?我怀疑 Google 的主页只允许 GET、HEAD 和 OPTIONS。

这是对 Google 的 POST 请求的正文,其中包含 Google 的解释。

405. 这是一个错误。

请求方法POST 不适用于URL /。这就是我们所知道的。

【讨论】:

  • 汤姆,你为什么要发帖?你想达到什么目的?如果您想获取搜索结果,您应该使用 GET。
  • 好的。我不应该使用 POST。但我发现我可以毫无错误地发帖到“yahoo.com”。
  • 每个网站都不同。例如,Apache 似乎默认允许 POST,但它实际上并没有做任何事情。
  • 如何允许/不允许get/post方法?
  • @kanishk:“不允许”的全部意义在于你不能这样做。这就是“不允许”的意思。您唯一的选择是做其他允许的事情。
猜你喜欢
  • 2021-08-10
  • 2013-11-04
  • 1970-01-01
  • 2021-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-07
  • 2019-09-05
相关资源
最近更新 更多