代碼提取(微信curl)

發現不少地方代碼重複了,由於作微信羣發不少地方須要模擬curlform表單上傳,因此提取了一個公共方法java

須要傳給這個方法你要上傳的文件file,你請求的accesstoken,和你的url緩存

// 公用的模擬curl上傳方法(微信)
	public static String curlForm(String accessToken, String url, File file) throws Exception {
		url = url.replaceAll("ACCESS_TOKEN", accessToken);
		String result = null;
		if (!file.exists() || !file.isFile()) {
			throw new IOException("文件不存在");
		}
		// 第一部分
		URL urlObj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

		// 設置關鍵值
		con.setRequestMethod("POST"); // 以Post方式提交表單,默認get方式
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false); // post方式不能使用緩存

		// 設置請求頭信息
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");

		// 設置邊界
		String BOUNDARY = "----------" + System.currentTimeMillis();
		con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

		// 請求正文信息
		// 第一部分:
		StringBuilder sb = new StringBuilder();
		sb.append("--"); // 必須多兩道線
		sb.append(BOUNDARY);
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
		sb.append("Content-Type:application/octet-stream\r\n\r\n");

		byte[] head = sb.toString().getBytes("utf-8");
		// 得到輸出流
		OutputStream out = new DataOutputStream(con.getOutputStream());
		// 輸出表頭
		out.write(head);

		// 文件正文部分
		// 把文件已流文件的方式 推入到url中
		DataInputStream in = new DataInputStream(new FileInputStream(file));
		int bytes = 0;
		byte[] bufferOut = new byte[1024];
		while ((bytes = in.read(bufferOut)) != -1) {
			out.write(bufferOut, 0, bytes);
		}
		in.close();

		// 結尾部分
		byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定義最後數據分隔線
		out.write(foot);
		out.flush();
		out.close();

		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		try {
			// 定義BufferedReader輸入流來讀取URL的響應
			reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				// System.out.println(line);
				buffer.append(line);
			}
			if (result == null) {
				result = buffer.toString();
			}
		} catch (IOException e) {
			System.out.println("發送POST請求出現異常!" + e);
			e.printStackTrace();
			throw new IOException("數據讀取異常");
		} finally {
			if (reader != null) {
				reader.close();
			}
		}
		return result;
	}
相關文章
相關標籤/搜索