微信上传永久素材接口开发(二)

于是咱们照猫画虎,将这段代码改一下,变成可以上传图片素材的程序:

public static String postFile(String url, String filePath) {
	File file = new File(filePath);
	if (!file.exists())
		return null;
	String result = null;
	try {
		URL url1 = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
		conn.setConnectTimeout(5000);
		conn.setReadTimeout(30000);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Connection", "Keep-Alive");
		conn.setRequestProperty("Cache-Control", "no-cache");
		String boundary = "-----------------------------" + System.currentTimeMillis();
		conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

		OutputStream output = conn.getOutputStream();
		output.write(("--" + boundary + "\r\n").getBytes());
		output.write(
				String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName())
						.getBytes());
		output.write("Content-Type: image/jpeg \r\n\r\n".getBytes());
		byte[] data = new byte[1024];
		int len = 0;
		FileInputStream input = new FileInputStream(file);
		while ((len = input.read(data)) > -1) {
			output.write(data, 0, len);
		}
		output.write(("\r\n--" + boundary + "\r\n\r\n").getBytes());
		output.flush();
		output.close();
		input.close();
		InputStream resp = conn.getInputStream();
		StringBuffer sb = new StringBuffer();
		while ((len = resp.read(data)) > -1)
			sb.append(new String(data, 0, len, "utf-8"));
		resp.close();
		result = sb.toString();
		System.out.println(result);
	} catch (ClientProtocolException e) {
		log.error("postFile,不支持http协议", e);
	} catch (IOException e) {
		log.error("postFile数据传输失败", e);
	}
	System.out.println(result);
	return result;
}

public static void main(String[] args) {
	String url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=So3cGezg-11111&type=image";
	postFile(url, "/Users/noname/Downloads/test.jpg");
}


这样上传视频和图片的就都全了。至于语音,暂时没有需求,不过估计代码也差不了多少。

在百度的时候看到许多兄弟在问,于是把这段代码贴出来,希望能够帮到有需要的兄弟。

上一篇:http://blog.csdn.net/oarsman/article/details/51538078

你可能感兴趣的:(JAVA开发)