http连接服务器的工具类

/*
 *
 * 描述:连接服务器的工具类
 * 
 * 
 */
package com.pencho.pai.util;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.pencho.pai.view.entity.FormFile;

/**
 * 连接服务器的工具类
 * 
 * 
 */
public class ConnectionUtil {

	/**
	 * get请求获取数据
	 * 
	 * @param url
	 * @return
	 */
	public static String requestInfo(String url) {
		HttpUriRequest request = new HttpGet(url);
		HttpClient httpClient = new DefaultHttpClient();
		String data = null;
		try {
			HttpResponse response = httpClient.execute(request);
			int status = response.getStatusLine().getStatusCode();
			if (status == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				data = EntityUtils.toString(entity).trim();
				data = new String(data.getBytes("ISO-8859-1"), "utf-8");
			} else {
				data = "HTTP " + status;
			}
		} catch (Exception e) {
			data = "HTTP " + e.getMessage();
			e.printStackTrace();
		}
		return data;
	}

	/**
	 * post请求获取数据
	 * 
	 * @param url
	 * @return
	 */
	public static String postInfo(String postUrl, HashMap<String, Object> map,
			List<FormFile> fileList) throws Exception {
		String result = null;
		HttpURLConnection conn = null;
		DataOutputStream outStream = null;
		InputStream inStream = null;
		try {
			String BOUNDARY = "--------------et567z"; // 数据分隔线
			String MULTIPART_FORM_DATA = "Multipart/form-data";

			URL url = new URL(postUrl);
			conn = (HttpURLConnection) url.openConnection();

			conn.setDoInput(true);// 允许输入
			conn.setDoOutput(true);// 允许输出
			conn.setUseCaches(false);// 不使用Cache
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA
					+ ";boundary=" + BOUNDARY);
			conn.connect();

			outStream = new DataOutputStream(conn.getOutputStream());

			StringBuilder params = new StringBuilder();
			if (map != null) {
				for (Map.Entry<String, Object> entry : map.entrySet()) {// 构造文本类型参数的实体数据
					params.append("--");
					params.append(BOUNDARY + "\r\n");
					params.append("Content-Disposition: form-data; name=\""
							+ entry.getKey() + "\"\r\n\r\n");
					params.append(entry.getValue());
					params.append("\r\n");
				}
				outStream.write(params.toString().getBytes());
			}

			if (fileList != null) {
				for (FormFile file : fileList) {
					// 上传的图片
					StringBuilder split = new StringBuilder();
					split.append("--");
					split.append(BOUNDARY);
					split.append("\r\n");
					split.append("Content-Disposition: form-data;name=\""
							+ file.getParameterName() + "\";filename=\""
							+ file.getFilname() + "\"\r\n");
					split.append("Content-Type: " + file.getContentType()
							+ "\r\n\r\n");
					outStream.write(split.toString().getBytes());
					if (file.getInStream() != null) {
						byte[] buffer = new byte[1024];
						int len = 0;
						while ((len = file.getInStream().read(buffer, 0, 1024)) != -1) {
							outStream.write(buffer, 0, len);
						}
						file.getInStream().close();
					} else {
						outStream.write(file.getData(), 0,
								file.getData().length);
					}
					outStream.write("\r\n".getBytes());
				}
			}
			byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();
			// 数据结束标志
			outStream.write(end_data);
			outStream.flush();

			int cah = conn.getResponseCode();
			if (cah == 200) {
				inStream = conn.getInputStream();
				byte[] buffer = new byte[1024];
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				int len = 0;
				while ((len = inStream.read(buffer)) != -1) {
					bos.write(buffer, 0, len);
				}
				inStream.close();
				result = new String(bos.toByteArray());
			} else {
				throw new RuntimeException("请求url失败:" + cah);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (outStream != null)
				try {
					outStream.close();
				} catch (Exception e) {
				}
			if (conn != null)
				try {
					conn.disconnect();
				} catch (Exception e) {
				}
		}
		return result;
	}

	/**
	 * 使用post请求发送
	 * 
	 * @param postURL
	 * @param fileList
	 * @return
	 * @throws Exception
	 */
	public static String postMediaInfo(String postURL, List<FormFile> fileList)
			throws Exception {
		String result = null;
		HttpURLConnection conn = null;
		DataOutputStream outStream = null;
		InputStream inStream = null;
		try {
			String BOUNDARY = "--------------et567z"; // 数据分隔线 
			String MULTIPART_FORM_DATA = "Multipart/form-data";

			URL url = new URL(postURL);
			conn = (HttpURLConnection) url.openConnection();

			conn.setDoInput(true);// 允许输入
			conn.setDoOutput(true);// 允许输出
			conn.setUseCaches(false);// 不使用Cache
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA
					+ ";boundary=" + BOUNDARY);
			conn.connect();

			outStream = new DataOutputStream(conn.getOutputStream());
			if (fileList != null) {
				for (FormFile file : fileList) {
					// 上传的图片
					StringBuilder split = new StringBuilder();
					split.append("--");
					split.append(BOUNDARY);
					split.append("\r\n");
					split.append("Content-Disposition: form-data;name=\""
							+ file.getParameterName() + "\";filename=\""
							+ file.getFilname() + "\"\r\n");
					split.append("Content-Type: " + file.getContentType()
							+ "\r\n\r\n");
					outStream.write(split.toString().getBytes());
					if (file.getInStream() != null) {
						byte[] buffer = new byte[1024];
						int len = 0;
						while ((len = file.getInStream().read(buffer, 0, 1024)) != -1) {
							outStream.write(buffer, 0, len);
						}
						file.getInStream().close();
					} else {
						outStream.write(file.getData(), 0,
								file.getData().length);
					}
					outStream.write("\r\n".getBytes());
				}
				byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();// 数据结束标志
				outStream.write(end_data);
			}
			outStream.flush();

			int cah = conn.getResponseCode();
			Log.v("cah", "cah-----"+cah);
			if (cah == 200) {
				inStream = conn.getInputStream();
				byte[] buffer = new byte[1024];
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				int len = 0;
				while ((len = inStream.read(buffer)) != -1) {
					bos.write(buffer, 0, len);
				}
				inStream.close();
				result = new String(bos.toByteArray());
			} else {
				throw new RuntimeException("请求url失败:" + cah);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (outStream != null)
				try {
					outStream.close();
				} catch (Exception e) {
				}
			if (conn != null)
				try {
					conn.disconnect();
				} catch (Exception e) {
				}
		}
		return result;
	}

	public static Bitmap getConnectionBitmap(String path) throws Exception {
		URL url;
		Bitmap bitmap = null;
		try {
			url = new URL(path);
			URLConnection conn = url.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 0;
			bitmap = BitmapFactory.decodeStream(is, null, options);
		} catch (IOException e) {
			throw e;
		}
		return bitmap;
	}

	// -------------------------测试

	public static String postMediaInfoVideo(String postURL, String filePath)
			throws Exception {
		String result = null;
		HttpURLConnection conn = null;
		DataOutputStream outStream = null;
		File file = new File(filePath);
		try {
			String BOUNDARY = "--------------et567z"; // 数据分隔线
			String MULTIPART_FORM_DATA = "Multipart/form-data";

			URL url = new URL(postURL);
			conn = (HttpURLConnection) url.openConnection();

			conn.setDoInput(true);// 允许输入
			conn.setDoOutput(true);// 允许输出
			conn.setUseCaches(false);// 不使用Cache
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA
					+ ";boundary=" + BOUNDARY);
			conn.connect();

			outStream = new DataOutputStream(conn.getOutputStream());
			if (filePath != null) {
				// 上传的图片
				StringBuilder split = new StringBuilder();
				split.append("--");
				split.append(BOUNDARY);
				split.append("\r\n");
				split.append("Content-Disposition: form-data;name=\""
						+ Constant.MEDIA_FILE_KEY + "\";filename=\"a.mp4\"\r\n");
				split.append("Content-Type: " + Constant.CONTENT_TYPE_VIDEO
						+ "\r\n\r\n");
				outStream.write(split.toString().getBytes());
				FileInputStream inStream = new FileInputStream(file);
				if (inStream != null) {
					byte[] buffer = new byte[1024];
					int len = 0;
					while ((len = inStream.read(buffer, 0, 1024)) != -1) {
						outStream.write(buffer, 0, len);
					}
					inStream.close();
				}
				outStream.write("\r\n".getBytes());
			}
			byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();// 数据结束标志
			outStream.write(end_data);
			outStream.flush();

			int cah = conn.getResponseCode();
			if (cah == 200) {
				result = 200 + "ok";
			} else {
				throw new RuntimeException("请求url失败:" + cah);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (outStream != null)
				try {
					outStream.close();
				} catch (Exception e) {
				}
			if (conn != null)
				try {
					conn.disconnect();
				} catch (Exception e) {
				}
		}
		return result;
	}

	public static String postInfo(String postURL, Map<String, String> params,
			byte[] backgroundImage, byte[] userImage, String charsetName)
			throws Exception {
		String result = null;
		try {
			String BOUNDARY = "--------------et567z"; // 数据分隔线
			String MULTIPART_FORM_DATA = "Multipart/form-data";

			URL url = new URL(postURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			conn.setDoInput(true);// 允许输入
			conn.setDoOutput(true);// 允许输出
			conn.setUseCaches(false);// 不使用Cache
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA
					+ ";boundary=" + BOUNDARY);

			// 上传文本
			StringBuilder sb = new StringBuilder();
			// 上传的表单参数部分,格式请参考文章
			for (Map.Entry<String, String> entry : params.entrySet()) {// 构建表单字段内容
				sb.append("--");
				sb.append(BOUNDARY);
				sb.append("\r\n");
				sb.append("Content-Disposition: form-data; name=\""
						+ entry.getKey() + "\"\r\n\r\n");
				sb.append(entry.getValue());
				sb.append("\r\n");
			}
			DataOutputStream outStream = new DataOutputStream(
					conn.getOutputStream());
			outStream.write(sb.toString().getBytes());// 发送表单字段数据

			// 上传的图片
			StringBuilder split = new StringBuilder();
			split.append("--");
			split.append(BOUNDARY);
			split.append("\r\n");
			split.append("Content-Disposition: form-data;name=\"myfile\";filename=\"temp.jpg\"\r\n");
			split.append("Content-Type: image/jpg\r\n\r\n");
			outStream.write(split.toString().getBytes());
			outStream.write(backgroundImage, 0, backgroundImage.length);
			outStream.write("\r\n".getBytes());
			byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();// 数据结束标志
			outStream.write(end_data);

			outStream.flush();
			int cah = conn.getResponseCode();
			if (cah == 200) {
				result = 200 + "ok";
			} else {
				throw new RuntimeException("请求url失败:" + cah);
			}
			outStream.close();
			conn.disconnect();
		} catch (IOException e) {
			e.printStackTrace();

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

		}
		return result;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值