httpcontentlengthcalculator.java

来自「MyUploader 是一款使用 http 协议(RFC 1867)用于上传文件」· Java 代码 · 共 100 行

JAVA
100
字号
/*
 * Copyright 2006-2007 JavaAtWork All rights reserved.
 * Use is subject to license terms.
 */
package javaatwork.myuploader.net;

import javaatwork.myuploader.domain.FormData;
import javaatwork.myuploader.domain.FormInputField;
import javaatwork.myuploader.domain.FormFileField;

/**
 * Class for calculating the content length of an http request. 
 *
 * @author Johannes Postma - JavaAtWork - http://www.javaatwork.com
 */
public class HTTPContentLengthCalculator {

	public static final int NEWLINE = 2;
	public static final int PARAMETER_LINE = 39;
	public static final int FILE_LINE = 52;
	public static final int CONTENT_TYPE_LINE = 14;

	private long length = 0;
	private int boundaryLength = 0;
	
	/**
	 * Returns the content length of a multipart message.
	 * 
	 * @param data The FormData.
	 * @param boundaryLength The length of the boundary.
	 * @return The content length.
	 */
	public long calculateContentLength(FormData data, int boundaryLength) {

		FormInputField[] formFields = data.getFormInputFields();
		FormFileField[] files = data.getFormFileFields();
		
		this.boundaryLength = boundaryLength;
		
		// initialise
		length = 0;

		if (formFields != null && formFields.length > 0) {
			calculateContentLength(formFields);
		}

		if (files != null && files.length > 0) {
			calculateContentLength(files);
		}

		// footer
		length += boundaryLength + 2;
		length += NEWLINE;

		return length;
	}

	/**
	 * Calculate the content length of the form input fields.
	 * 
	 * @param formInputFields An array of FormInputField.
	 */
	private void calculateContentLength(FormInputField[] formInputFields) {

		for (int i = 0; i < formInputFields.length; i++) {
			length += boundaryLength;
			length += NEWLINE;
			length += PARAMETER_LINE;
			length += formInputFields[i].getName().length();
			length += NEWLINE;
			length += NEWLINE;
			length += formInputFields[i].getValue().length();
			length += NEWLINE;
		}
	}

	/**
	 * Calculate the contentlength of the form file fields.
	 * 
	 * @param formFileFields An array of FormFileField
	 */
	private void calculateContentLength(FormFileField[] formFileFields) {

		for (int i = 0; i < formFileFields.length; i++) {
			length += boundaryLength;
			length += NEWLINE;
			length += FILE_LINE;
			length += formFileFields[i].getName().length(); // parameter name
			length += formFileFields[i].getURLEncodedUploadName().length();
			length += NEWLINE;
			length += CONTENT_TYPE_LINE;
			length += formFileFields[i].getContentType().length();
			length += NEWLINE;
			length += NEWLINE;
			length += formFileFields[i].getFile().length();
			length += NEWLINE;
		}
	}
}

⌨️ 快捷键说明

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