⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httpconnection.java

📁 javaP2P技术内幕课程19-20的源代码
💻 JAVA
字号:
// A simple HTTP class.

package ch20.peer;

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

public class HttpConnection {
	
	private String file_name,host_name;
	private Socket httpSocket=null;
	private StringBuffer HTTPRequest; 
	private StringBuffer requestProperties = new StringBuffer();
	private InputStream in = null;
	private OutputStream out = null;
	String contentType;
	String requestMethod;
	String HTTPRequestPayload;


	//constructor
	public HttpConnection ( String url, 
					int port, 
					String contentType,
					String requestMethod,
					String HTTPRequestPayload
	) throws UnknownHostException, IOException {
		
		HTTPRequest = new StringBuffer();
		
		//Resolve the user passed URL
		//into host and file names.
		String subStringWithOutHTTP = url.substring (7);
		int slashPosition = subStringWithOutHTTP.indexOf ("/");
		file_name = subStringWithOutHTTP.substring (slashPosition);
		host_name = subStringWithOutHTTP.substring (0,slashPosition);
		
		httpSocket = new Socket(host_name,port);

		this.contentType= contentType;
		this.requestMethod = requestMethod;
		this.HTTPRequestPayload = HTTPRequestPayload;

	}//HttpConnection()
	
		
	//Sets a request property.
	public void setRequestProperty (String name, String value){
		if (requestProperties.capacity()==0) {
			requestProperties = new StringBuffer();
		}
		requestProperties.append(name+" "+value+"\r\n");
	}// end setRequestProperty()
	
	//Send the HTTP request synchronously.	
	public String call(){

		HTTPRequest.append(requestMethod + " "+file_name+" HTTP/1.1\r\n");
		HTTPRequest.append("Host: "+host_name+"\r\n");
		HTTPRequest.append("Content-type: "+ contentType +
				"; charset=utf-8\r\n");
		HTTPRequest.append("Content-length:" 
			+ String.valueOf(HTTPRequestPayload.length())
			+ "\r\n");
		String HTTPRequestString = HTTPRequest.toString();

		requestProperties.append("\r\n");
		HTTPRequestString +=requestProperties.toString();
		HTTPRequestString +=HTTPRequestPayload;

		try{
			PrintWriter out = 
				new PrintWriter(httpSocket.getOutputStream());
			BufferedReader in = 
				new BufferedReader(
				new InputStreamReader(httpSocket.getInputStream()));	
			
			// sending request to output stream	
			out.println(HTTPRequestString);
			out.flush();
			
			StringBuffer sc = new StringBuffer();
			String line = null;

			while((line=in.readLine())!=null){
				sc.append(line);
				sc.append("\r\n");
			}
			
			// closing input and output streams 	
			String response = sc.toString();
			in.close();
			out.close();

			return response;

		}catch (Exception e){
			return null;
		}//catch
	}// end getHeaders()

}// end class

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -