使用Java中的HTTP套接字编程从URL读取索引文件

时间:2017-03-22 12:20:09

标签: java sockets http

我的问题是,我无法使用HTTP套接字从给定的URL读取文本。例如,我想从88.88.8.8/text.txt中读取并在命令行上打印内容但它仍然卡在读取部分而没有任何错误:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Base64;

public class Program {

    static final int PORT_NO = 80;

    static Socket m_socket;

    static String m_server;
    static String m_index;
    static String m_authString;

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

        try {        
            setConnectionInfoFromArgs(args);         
            m_socket = new Socket(m_server, PORT_NO);

            loginToServer();

            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(m_socket.getOutputStream()))); 
            out.print("GET /" + m_index + " HTTP/1.1"); 
            out.print("\r\n");
            out.flush();

            BufferedReader input = new BufferedReader(new InputStreamReader(m_socket.getInputStream()));
            String line;

            while((line = input.readLine()) != null) {
                System.out.println(line); //Gets stuck here
            }
        } catch (Exception e) {
            System.out.println("Unable to connect!");
            System.out.println("Be sure to enter correct URL and authentication.");
        }
        finally {
            System.exit(0);
        }
    }

    public static void setConnectionInfoFromArgs(String[] args) {
        String[] url = args[0].split("/");
        m_server = url[0];
        m_index = url[1];

        //Encode "userName:password" to Base64
        byte[] encodedBytes = Base64.getEncoder().encode(args[1].getBytes());
        m_authString = new String(encodedBytes);
    }

    private static void loginToServer() throws IOException {       
          DataOutputStream auth = new DataOutputStream(m_socket.getOutputStream());
          auth.writeBytes("Authorization: Basic " + m_authString);
    }
}

1 个答案:

答案 0 :(得分:0)

好的,我做了一些研究,结果发现我的主机标题缺乏,因为Remy Lebeau说,并且授权部分没有正确地包含在标题中。下面的代码解决了这个问题:

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(m_socket.getOutputStream())), false);
            out.print("GET /" + m_index + " HTTP/1.1\r\n"
                    + "Host: " + m_server + "\r\n"
                    + "Authorization: Basic " + m_authString + "\r\n"
                    + "Connection: close\r\n\r\n");
            out.flush();