2012-03-07 91 views
0

我找到以下Web服务器类here。我需要编写一个Android应用程序(客户端),它可以从此服务器检索文件。如果有人能够帮助我做到这一点,那将是非常棒的。谢谢。如何从http服务器检索文件

服务器主机地址是:MY-PC/ip地址

当我执行客户端它提供了一个例外。

java.net.ConnectException:连接被拒绝:连接

WebServer.Java

import java.io.*; 
import java.net.*; 


public class WebServer extends Thread { 

public WebServer() { 

    this.start(); 
} 

private void displayString(String string) { //an alias to avoid typing so much! 
    System.out.println(string); 
} 

private static final int UMBRA_PORT = 30480; 
private static final int ROOM_THROTTLE = 200; 
private InetAddress hostAddress; 

//this is a overridden method from the Thread class we extended from 
public void run() { 
    //we are now inside our own thread separated from the gui. 
    ServerSocket serversocket = null; 
    //To easily pick up lots of girls, change this to your name!!! 
    displayString("The simple httpserver v. 0000000000\nCoded by Jon Berg" + 
      "<jon.berg[on server]turtlemeat.com>\n\n"); 
    //Pay attention, this is where things starts to cook! 
    try { 
     //print/send message to the guiwindow 
     displayString("Trying to bind to localhost on port " + Integer.toString(UMBRA_PORT) + "..."); 
     //make a ServerSocket and bind it to given port, 
     //serversocket = new ServerSocket(port); 
    } 
    catch (Exception e) { //catch any errors and print errors to gui 
     displayString("\nFatal Error:" + e.getMessage()); 
     return; 
    } 

    // Attempt to get the host address 
    try 
    { 
     hostAddress = InetAddress.getLocalHost(); 
    } 
    catch(UnknownHostException e) 
    { 
     System.out.println("Could not get the host address."); 
     return; 
    } 
    // Announce the host address 
    System.out.println("Server host address is: "+hostAddress); 
    // Attempt to create server socket 
    try 
    { 
     serversocket = new ServerSocket(UMBRA_PORT,0,hostAddress); 
    } 
    catch(IOException e) 
    { 
     System.out.println("Could not open server socket."); 
     return; 
    } 
    // Announce the socket creation 
    System.out.println("Socket "+serversocket+" created."); 



    displayString("OK!\n"); 
    //go in a infinite loop, wait for connections, process request, send response 
    while (true) { 
     displayString("\nReady, Waiting for requests...\n");   

     try { 

      //this call waits/blocks until someone connects to the port we 
      //are listening to 
      Socket connectionsocket = serversocket.accept(); 
      //figure out what ipaddress the client commes from, just for show! 
      InetAddress client = connectionsocket.getInetAddress(); 
      //and print it to gui 
      displayString(client.getHostName() + " connected to server.\n"); 
      //Read the http request from the client from the socket interface 
      //into a buffer. 
      BufferedReader input = 
        new BufferedReader(new InputStreamReader(connectionsocket. 
          getInputStream())); 
      //Prepare a outputstream from us to the client, 
      //this will be used sending back our response 
      //(header + requested file) to the client. 
      DataOutputStream output = 
        new DataOutputStream(connectionsocket.getOutputStream()); 

      //as the name suggest this method handles the http request, see further down. 
      //abstraction rules 
      http_handler(input, output); 
     } 
     catch (Exception e) { //catch any errors, and print them 
      displayString("\nError:" + e.getMessage()); 
     } 

    } //go back in loop, wait for next request 
} 

//our implementation of the hypertext transfer protocol 
//its very basic and stripped down 
private void http_handler(BufferedReader input, DataOutputStream output) { 
    int method = 0; //1 get, 2 head, 0 not supported 
    String http = new String(); //a bunch of strings to hold 
    String path = new String(); //the various things, what http v, what path, 
    String file = new String(); //what file 
    String user_agent = new String(); //what user_agent 
    try { 
     //This is the two types of request we can handle 
     //GET /index.html HTTP/1.0 
     //HEAD /index.html HTTP/1.0 
     String tmp = input.readLine(); //read from the stream 
     String tmp2 = new String(tmp); 
     tmp.toUpperCase(); //convert it to uppercase 
     if (tmp.startsWith("GET")) { //compare it is it GET 
      method = 1; 
     } //if we set it to method 1 
     if (tmp.startsWith("HEAD")) { //same here is it HEAD 
      method = 2; 
     } //set method to 2 

     if (method == 0) { // not supported 
      try { 
       output.writeBytes(construct_http_header(501, 0)); 
       output.close(); 
       return; 
      } 
      catch (Exception e3) { //if some error happened catch it 
       displayString("error:" + e3.getMessage()); 
      } //and display error 
     } 
     //} 

     //tmp contains "GET /index.html HTTP/1.0 ......." 
     //find first space 
     //find next space 
     //copy whats between minus slash, then you get "index.html" 
     //it's a bit of dirty code, but bear with me... 
     int start = 0; 
     int end = 0; 
     for (int a = 0; a < tmp2.length(); a++) { 
      if (tmp2.charAt(a) == ' ' && start != 0) { 
       end = a; 
       break; 
      } 
      if (tmp2.charAt(a) == ' ' && start == 0) { 
       start = a; 
      } 
     } 
     path = tmp2.substring(start + 2, end); //fill in the path 
    } 
    catch (Exception e) { 
     displayString("errorr" + e.getMessage()); 
    } //catch any exception 

    //path do now have the filename to what to the file it wants to open 
    displayString("\nClient requested:" + new File(path).getAbsolutePath() + "\n"); 
    FileInputStream requestedfile = null; 

    try { 

     //try to open the file, 
     requestedfile = new FileInputStream(path); 
    } 
    catch (Exception e) { 
     try { 
      //if you could not open the file send a 404 
      output.writeBytes(construct_http_header(404, 0)); 
      //close the stream 
      output.close(); 
     } 
     catch (Exception e2) {} 
     displayString("error" + e.getMessage()); 
    } //print error to gui 

    //happy day scenario 
    try { 
     int type_is = 0; 
     //find out what the filename ends with, 
     //so you can construct a the right content type 
     if (path.endsWith(".zip")) { 
      type_is = 3; 
     } 
     if (path.endsWith(".jpg") || path.endsWith(".jpeg")) { 
      type_is = 1; 
     } 
     if (path.endsWith(".gif")) { 
      type_is = 2;  
     } 
     if (path.endsWith(".ico")) { 
      type_is = 4; 
     } 
     if (path.endsWith(".xml")) { 
      type_is = 5; 
     } 
     //write out the header, 200 ->everything is ok we are all happy. 
     output.writeBytes(construct_http_header(200, 5)); 

     //if it was a HEAD request, we don't print any BODY 
     if (method == 1) { //1 is GET 2 is head and skips the body 
      byte [] buffer = new byte[1024]; 
      while (true) { 
       //read the file from filestream, and print out through the 
       //client-outputstream on a byte per byte base. 
       int b = requestedfile.read(buffer, 0,1024); 
       if (b == -1) { 
        break; //end of file 
       } 
       output.write(buffer,0,b); 
      } 
      //clean up the files, close open handles 

     } 
     output.close(); 
     requestedfile.close(); 
    } 

    catch (Exception e) {} 

} 

//this method makes the HTTP header for the response 
//the headers job is to tell the browser the result of the request 
//among if it was successful or not. 
private String construct_http_header(int return_code, int file_type) { 
    String s = "HTTP/1.0 "; 
    //you probably have seen these if you have been surfing the web a while 
    switch (return_code) { 
    case 200: 
     s = s + "200 OK"; 
     break; 
    case 400: 
     s = s + "400 Bad Request"; 
     break; 
    case 403: 
     s = s + "403 Forbidden"; 
     break; 
    case 404: 
     s = s + "404 Not Found"; 
     break; 
    case 500: 
     s = s + "500 Internal Server Error"; 
     break; 
    case 501: 
     s = s + "501 Not Implemented"; 
     break; 
    } 

    s = s + "\r\n"; //other header fields, 
    s = s + "Connection: close\r\n"; //we can't handle persistent connections 
    s = s + "Server: SimpleHTTPtutorial v0\r\n"; //server name 

    switch (file_type) { 
    //plenty of types for you to fill in 
    case 0: 
     break; 
    case 1: 
     s = s + "Content-Type: image/jpeg\r\n"; 
     break; 
    case 2: 
     s = s + "Content-Type: image/gif\r\n"; 
     break; 
    case 3: 
     s = s + "Content-Type: application/x-zip-compressed\r\n"; 
     break; 
    case 4: 
     s = s + "Content-Type: image/x-icon\r\n"; 
    case 5: 
     s = s + "Content-Type: text/xml\r\n"; 
     break; 
    default: 
     s = s + "Content-Type: text/html\r\n"; 
     break; 
    } 

    ////so on and so on...... 
    s = s + "\r\n"; //this marks the end of the httpheader 
    //and the start of the body 
    //ok return our newly created header! 
    return s; 
} 

} 

Client.Java

public class WatchMeManagerClient { 

private static Socket socket; 
private static PrintWriter printWriter; 

public static void main(String[] args) throws Exception { 
    try { 
     URL url; 
     URLConnection urlConn; 
     DataInputStream dis; 

     url = new URL("http://ipaddress/xml/userGroup.xml"); 

     urlConn = url.openConnection(); 
     urlConn.setDoInput(true); 
     urlConn.setUseCaches(false); 

     dis = new DataInputStream(urlConn.getInputStream()); 
     String s; 

     while ((s = dis.readLine()) != null) { 
      System.out.println(s); 
     } 
     dis.close(); 
    } 

    catch (MalformedURLException mue) { 
     System.out.println(mue.toString()); 
    } catch (IOException ioe) { 
     System.out.println(ioe.toString()); 
    } 
} 
} 

当我运行在PC上它的工作原理的代码。但是当我尝试在Android设备上执行它时,会出现以下错误。

+0

您是否连接到正确的端口?服务器正在侦听端口30480,因此您应该连接到http:// ipaddress:30480/xml/userGroup.xml。 – Petter 2012-03-07 07:56:43

+0

谢谢佩特。有用。再次感谢你。 – Sha 2012-03-07 08:07:50

回答

0

这样的问题下面的任一原因导致:

  1. 端口是错误的

  2. 防火墙阻止它。

0

使用套接字需要以下权限,我认为你缺少:

​​
0

你允许你的清单上网吗?

<uses-permission android:name="android.permission.INTERNET"/> 
相关问题