httpentity.java

来自「使用java实现的RFC1945 http1.0协议。所有面向对象设计严谨按照R」· Java 代码 · 共 110 行

JAVA
110
字号
/**
 * 
 */
package edu.sysu.http.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import edu.sysu.http.util.HttpMediaTypeManager;

/**
 * @author Administrator
 * 
 */
public class HttpEntity {

	protected HttpType contentType;
	protected long length = 0L;
	protected InputStream content;
	private byte[] byteContent;

	public InputStream getContent() {
		return content;
	}

	public void setContent(InputStream content) {
		this.content = content;
	}

	/**
	 * 
	 */
	public HttpEntity() {
		// TODO Auto-generated constructor stub
	}
	
	public HttpEntity(InputStream content) throws IOException {
		// TODO Auto-generated constructor stub
		this.setContent(content);
		this.setLength(content.available());
		this.byteContent = new byte[this.getLength().intValue()];
		this.getContent().read(this.byteContent);
	}
	
	public HttpEntity(String absolutePath) throws IOException {
		// TODO Auto-generated constructor stub
		this.readFrom(absolutePath);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	public void setContentType(HttpType contentType) {
		this.contentType = contentType;
	}

	public HttpType getContentType() {
		return contentType;
	}

	public void setLength(long length) {
		this.length = length;
	}

	public Long getLength() {
		return length;
	}

	public void writeTo(final OutputStream outstream) throws IOException {
		if (outstream == null) {
			throw new IllegalArgumentException("Output stream may not be null");
		}
		InputStream instream = getContent();
		int l;
		byte[] tmp = new byte[2048];
		while ((l = instream.read(tmp)) != -1) {
			outstream.write(tmp, 0, l);
		}
	}

	public void readFrom(final String absolutePath) throws IOException {
		if (absolutePath == null) {
			throw new IllegalArgumentException("Output stream may not be null");
		}
		File file = new File(absolutePath);
		this.content = new FileInputStream(file);
		
		this.setContentType(HttpMediaTypeManager.getInstance().getType(file));
		this.setLength(file.length());
		this.byteContent = new byte[this.getLength().intValue()];
		this.content.read(this.byteContent);
	}

	public String toString() {
		if(this.byteContent != null)
			return new String(this.byteContent);
		else
			return null;
	}

}

⌨️ 快捷键说明

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