Android中Form Post方式提交,上传文件的实现

package com.zzz.Test;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONObject;

import android.net.Uri;

public class HttpFormPost {
	public static final int RESULT_POST_SUCCESS = 0;
	public static final int RESULT_POST_FAILED = -1;

	private static final String TWOHYPHENS = "--";
	private static final String END = "\r\n";

	private String mPostUrl = "";
	private String mErrorMessage = "";
	private String mCharset = "UTF-8";
	private String mBoundary = "----UploadPhotoAAbbCCaajksdafsdjkafwewrwe";

	HttpFormPost(String postUrl) {
		this(postUrl, null, null);
	}

	HttpFormPost(String postUrl, String charset, String boundary) {
		setPostUrl(postUrl);
		setCharset(charset);
		setBoundary(boundary);
	}

	private final void setPostUrl(String postUrl) {
		if( postUrl != null)
			mPostUrl = postUrl;
	}

	private final String getErrorMessage() {
		return mErrorMessage;
	}

	private final void setCharset(String charset) {
		if (charset != null)
			mCharset = charset;
	}

	private final void setBoundary(String boundary) {
		if (boundary != null)
			mBoundary = boundary;
	}

	private final String buildTextField(String field, String value) {
		StringBuilder sb = new StringBuilder();
		sb.append(TWOHYPHENS + mBoundary + END);

		sb.append("Content-Disposition: form-data; " + "name=\"" + field + "\""
				+ END);
		sb.append(END);
		sb.append(value + END);

		return sb.toString();
	}

	private final String buildTextField(NameValuePair field) {
		return buildTextField(field.getName(), field.getValue());
	}

	private final String buildFileField(String filePath) {
		StringBuilder sb = new StringBuilder();
		sb.append(TWOHYPHENS + mBoundary + END);

		sb.append("Content-Disposition: form-data; "
				+ "name=\"file\";filename=\"" + filePath + "\"" + END);
		sb.append(END);
		return sb.toString();

	}

	public final int upload(List<NameValuePair> fields, String[] files) {
		int retCode = RESULT_POST_FAILED;

		try {

			URL actionUrl = new URL(mPostUrl);
			HttpURLConnection connection = (HttpURLConnection) actionUrl
					.openConnection();
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Charset", mCharset);
			connection.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + mBoundary);

			DataOutputStream out = new DataOutputStream(
					connection.getOutputStream());

			if (fields != null && fields.size() > 0) {
				StringBuilder fieldBuilder = new StringBuilder();
				for (NameValuePair field : fields) {
					fieldBuilder.append(buildTextField(field));
				}
				out.write(fieldBuilder.toString().getBytes(mCharset));
			}

			if (files != null && files.length > 0) {
				for (String f : files) {
					out.write(buildFileField(f).toString().getBytes(mCharset));

					FileInputStream fis = new FileInputStream(f);
					int bufferSize = 1024;
					byte[] buffer = new byte[bufferSize];

					int length = -1;
					while ((length = fis.read(buffer)) != -1) {
						out.write(buffer, 0, length);
					}

					out.write(END.getBytes(mCharset));

					fis.close();
					out.flush();

				}
			}

			out.writeBytes(END);
			out.writeBytes(TWOHYPHENS + mBoundary + TWOHYPHENS + END);

			InputStream is = connection.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			out.close();

			JSONObject result = MyUtil.getJO(b.toString());
			if (result.getString("result") == "true") {
				retCode = RESULT_POST_SUCCESS;
			} else {
				mErrorMessage = result.getString("message");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retCode;
	}

	public final String post(List<NameValuePair> fields) {
		try {

			URL actionUrl = new URL(mPostUrl);
			HttpURLConnection connection = (HttpURLConnection) actionUrl
					.openConnection();
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Charset", mCharset);
			connection.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + mBoundary);

			DataOutputStream out = new DataOutputStream(
					connection.getOutputStream());

			if (fields != null && fields.size() > 0) {
				StringBuilder fieldBuilder = new StringBuilder();
				for (NameValuePair field : fields) {
					fieldBuilder.append(buildTextField(field));
				}
				out.write(fieldBuilder.toString().getBytes(mCharset));
			}

			out.writeBytes(END);
			out.writeBytes(TWOHYPHENS + mBoundary + TWOHYPHENS + END);

			InputStream is = connection.getInputStream();
			int ch;
			int i = 0;
			byte[] mybuf = new byte[1024*128];
			
			while ((ch = is.read()) != -1) {
				mybuf[i++]=(byte)ch;
			}
			out.close();

			String s1 = new String(mybuf, "utf-8");
			return s1;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值