HttpURLConnection post 请求

最近在重构项目,去掉HttpClient,直接使用HttpURLConnection。

 

这里先讲一下它的POST 模拟表单上传。

1、一些常量的初始化:

public static final String BOUNDARY = "7csd4bisk2sdfk41sdfa00sskiea6d158c";
public static final String MP_BOUNDARY = "--" + BOUNDARY;
public static final String END_MP_BOUNDARY = "--" + BOUNDARY + "--";
public static final String MULTIPART_FORM_DATA = "multipart/form-data";


2、HttpURLConnection 的初始化:

protected HttpURLConnection initConnection(URL url, String method) {
		HttpURLConnection connection = null;
		try {
			connection = (HttpURLConnection) url.openConnection();
			int timeoutMs =3*1000;
			connection.setConnectTimeout(timeoutMs);
			connection.setReadTimeout(timeoutMs);
			connection.setUseCaches(false);
			connection.setRequestMethod(method);
			connection.setDoInput(true);
			connection.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			
			String userAgent = "xxxxxxx";//定义自己的UserAgent,当然你也可以使用默认的。
			connection.setRequestProperty("User-Agent", userAgent);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return connection;
	}


3、请求参数:

String url = "http://www.baidu.com/";

HashMap<String,String> param = new HashMap<String,String>();
param.put("token", "123456");//要上传的键值对
param.put("pic", "/storage/new.png");//要上传的图片


4、发送请求:

/**
	 * 向服务器发送数据
	 * 
	 * @param requestPath
	 *            请求的服务器接口
	 * @param imgPath
	 *            如果有图片,就设置为图片的路径。如果没有,就设置为null
	 * @param bundle
	 *            请求参数
	 * @param method
	 *            POST 或者 GET
	 * @return
	 */
	protected String sendMessage2Server(String requestPath, String imageKey, HashMap<String, Object> param, String method) {
		String result = "";
		try {
			URL mUrl = new URL(url);
			HttpURLConnection connection = initConnection(mUrl, method);
			connection.connect();

			DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
			String imgPath = param.get(imageKey) + "";
			param.remove(imageKey);
			paramToUpload(dos, param, requestPath);
			if (!TextUtils.isEmpty(imgPath)) {
				Bitmap bf = BitmapFactory.decodeFile(imgPath);
				imageContentToUpload(dos, bf, "pic", "new.png");
			} else {
				try {
					dos.write(("\r\n" + END_MP_BOUNDARY + "\r\n").getBytes());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			// 根据ResponseCode判断连接是否成功
			int responseCode = connection.getResponseCode();
			if (responseCode != 200) {
				result = null;
			} else {
				// 定义BufferedReader输入流来读取URL的ResponseData
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				String line;
				StringBuffer responseResult = new StringBuffer();
				while ((line = bufferedReader.readLine()) != null) {
					responseResult.append(line);
				}
				result = responseResult.toString();
				LogUtils.e("upload", result);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}


5、上传文本:

/**
	 * 上传文本
	 * @param baos
	 * @param param
	 * @param requestPath
	 */
	private void paramToUpload(OutputStream baos, HashMap<String, Object> param,) {
		
		

		Set<String> set = param.keySet();
		Iterator<String> keys = set.iterator();
		while (keys.hasNext()) {
			String key = keys.next();
			String value = param.get(key) + "";

			StringBuilder temp = new StringBuilder(10);
			temp.setLength(0);
			temp.append(MP_BOUNDARY).append("\r\n");
			temp.append("content-disposition: form-data; name=\"").append(key).append("\"\r\n\r\n");
			temp.append(value).append("\r\n");
			byte[] res = temp.toString().getBytes();
			try {
				baos.write(res);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

6、上传图片

/**
	 * 上传图片
	 * @param out
	 * @param imgpath 图片路径
	 * @param name 
	 * @param fileName
	 */
	protected void imageContentToUpload(OutputStream out, Bitmap imgpath, String name, String fileName) {
		StringBuilder temp = new StringBuilder();

		temp.append(MP_BOUNDARY).append("\r\n");
		temp.append("Content-Disposition: form-data; name=\"");
		temp.append(name);
		temp.append("\"; filename=\"").append(fileName).append("\"\r\n");
		String filetype = "image/jpeg";
		temp.append("Content-Type: ").append(filetype).append("\r\n\r\n");
		byte[] res = temp.toString().getBytes();
		try {
			out.write(res);
			imgpath.compress(CompressFormat.JPEG, 75, out);
			out.write("\r\n".getBytes());
			out.write(("\r\n" + END_MP_BOUNDARY + "\r\n").getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值