上传带图片的Http请求
博客专区 > SuShine 的博客 > 博客详情
上传带图片的Http请求
SuShine 发表于2年前
上传带图片的Http请求
  • 发表于 2年前
  • 阅读 11
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 十分钟定制你的第一个小程序>>>   

/**
	 * 上传带图片的http请求
	 * 
	 * @param murl网址
	 * @param map
	 *            参数对 主要不要包括图片
	 * @param path
	 *            图片路径 也可以是其他格式 自行做
	 * @return
	 * @throws Exception
	 */
	static public String post(String murl, HashMap<String, String> map,
			String path) throws Exception {
		File file = new File(path);
		String filename = path.substring(path.lastIndexOf("/"));
		// String filename = Str.md5(path);
		StringBuilder sb = new StringBuilder();
		if (null != map) {
			for (Map.Entry<String, String> entry : map.entrySet()) {
				sb.append("--" + BOUNDARY + "\r\n");
				sb.append("Content-Disposition: form-data; name=\""
						+ entry.getKey() + "\"" + "\r\n");
				sb.append("\r\n");
				sb.append(entry.getValue() + "\r\n");

			}
		}

		sb.append("--" + BOUNDARY + "\r\n");
		sb.append("Content-Disposition: form-data; name=\"image\"; filename=\""
				+ filename + "\"" + "\r\n");

		sb.append("Content-Type: image/pjpeg" + "\r\n");
		sb.append("\r\n");

		byte[] before = sb.toString().getBytes("UTF-8");
		byte[] after = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");

		URL url = new URL(murl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type",
				"multipart/form-data; boundary=" + BOUNDARY);

		conn.setRequestProperty("Authorization",
				"Bearer " + Douban.getAccessToken());
		conn.setRequestProperty("Content-Length",
				String.valueOf(before.length + file.length() + after.length));
		conn.setRequestProperty("HOST", url.getHost());
		conn.setDoOutput(true);

		OutputStream out = conn.getOutputStream();
		InputStream in = new FileInputStream(file);

		out.write(before);

		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) != -1)
			out.write(buf, 0, len);

		out.write(after);

		in.close();
		out.close();
		MLog.e(inputStream2String(conn.getInputStream()) + "");
		return conn.getContent().toString();

	}

	/**
	 * is转String
	 * 
	 * @param in
	 * @return
	 * @throws IOException
	 */
	public static String inputStream2String(InputStream in) throws IOException {
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[4096];
		for (int n; (n = in.read(b)) != -1;) {
			out.append(new String(b, 0, n));
		}
		return out.toString();
	}

共有 人打赏支持
粉丝 118
博文 303
码字总数 78170
×
SuShine
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: