我无法理解 http 请求的响应

为什么它给我一个405错误,尽管代码应该在逻辑上工作,链接有一个有效的下载,我从互联网上复制一些工作代码,看看发生了什么,如这个主题如何下载一个图像与Java socket HTTP / 1.1请求?它也没有给我一个响应200?

很抱歉混乱的代码我试图找出问题大约2天

//package htmlconnection;


import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.ByteArrayOutputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.MalformedURLException;

import java.net.Socket;

import java.net.URL;

import java.net.UnknownHostException;

import java.nio.charset.StandardCharsets;

import javax.net.SocketFactory;

import javax.net.ssl.HttpsURLConnection;

import javax.net.ssl.SSLSocketFactory;

public class MyClass {

    public static void main(String args[])throws UnknownHostException, IOException {

        try {

            URL url =new URL("http://www.ncert.nic.in/NCERTS/l/jemh1an.pdf");

            String path=url.getPath();

            String domain=url.getHost();

            System.out.println(path);

            System.out.println(domain);

            Socket socket = new Socket(domain,80);

            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));

            System.out.println(socket.isConnected());

            out.println("Get "+path+" HTTP/1.1\n" +"Host: "+domain);

            out.println();

            out.flush();

            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            String inputLine;

            while ((inputLine = in.readLine()) != null && inputLine.trim() != "0") {

               System.out.println(inputLine);

            }

        } catch (MalformedURLException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

}


收到一只叮咚
浏览 114回答 2
2回答

莫回无

GET 请求必须全部为大写字母。您可以看到您得到的是 405,这意味着此处不接受 HTTP 请求方法:<title>405&nbsp;-&nbsp;HTTP&nbsp;verb&nbsp;used&nbsp;to&nbsp;access&nbsp;this&nbsp;page&nbsp;is&nbsp;not&nbsp;allowed.</title>更改此项:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out.println("Get&nbsp;"+path+"&nbsp;HTTP/1.1\n"&nbsp;+"Host:&nbsp;"+domain);对此:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out.println("GET&nbsp;"+path+"&nbsp;HTTP/1.1\n"&nbsp;+"Host:&nbsp;"+domain);

四季花海

HTTP 动词应该是区分大小写的。下面是指向 HTTP/1.1 规范的链接。使用“获取”而不是“获取”。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java