為什么它給我一個405錯誤,盡管代碼應(yīng)該在邏輯上工作,鏈接有一個有效的下載,我從互聯(lián)網(wǎng)上復(fù)制一些工作代碼,看看發(fā)生了什么,如這個主題如何下載一個圖像與Java socket HTTP / 1.1請求?它也沒有給我一個響應(yīng)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(); } }}
2 回答

莫回?zé)o
TA貢獻(xiàn)1865條經(jīng)驗 獲得超7個贊
GET 請求必須全部為大寫字母。您可以看到您得到的是 405,這意味著此處不接受 HTTP 請求方法:
<title>405 - HTTP verb used to access this page is not allowed.</title>
更改此項:
out.println("Get "+path+" HTTP/1.1\n" +"Host: "+domain);
對此:
out.println("GET "+path+" HTTP/1.1\n" +"Host: "+domain);

四季花海
TA貢獻(xiàn)1811條經(jīng)驗 獲得超5個贊
添加回答
舉報
0/150
提交
取消