程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-05(1)

如何用java实现post请求外部接口(字符串+文件参数)

发布于2020-11-19 20:51     阅读(1222)     评论(0)     点赞(17)     收藏(0)


最近在写证照识别业务,其中证照识别的接口是在调研用,选择了face++的,因为可支持自定义模板,等我有空的时候,会把全部业务流程整理出来,这里先把调用外部接口的方法写了出来。

示例代码:

JSONObject jsonObject = InterfaceUtil.doPost(TEMPLATE_OCR_URL,
				buildTextMap(), buildFileMap(file));
				
   // 传入api_key、api_secret这两个参数,类型为字符串。
	private Map<String, String> buildTextMap() {
		Map<String, String> textMap = new HashMap<String, String>();
		textMap.put("api_key", API_KEY);
		textMap.put("api_secret", API_SECRET);
		return textMap;
	}

    // 传一个叫image_file的MultipartFile格式参数。
	private Map<String, MultipartFile> buildFileMap(MultipartFile file) {
		Map<String, MultipartFile> fileMap = new HashMap<String, MultipartFile>();
		fileMap.put("image_file", file);
		return fileMap;
	}

工具类:



import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

import org.springframework.web.multipart.MultipartFile;

import com.alibaba.rocketmq.shade.com.alibaba.fastjson.JSONObject;

public class InterfaceUtil {
	/**
	 * 表单形式上传数据
	 * 
	 * @param urlStr  接口地址
	 * @param textMap 字符串参数
	 * @param fileMap 文件参数
	 * @param contentType 没有传入文件类型默认采用application/octet-stream
	 *                    contentType非空采用filename匹配默认的图片类型
	 * @return 返回response数据
	 */
	@SuppressWarnings("rawtypes")
	public static JSONObject doPost(String urlStr, Map<String, String> textMap,
			Map<String, MultipartFile> fileMap) {
		JSONObject jsonObject = null;
		HttpURLConnection conn = null;
		// boundary就是request头和上传文件内容的分隔符
		String BOUNDARY = "---------------------------123821742118716";
		try {
			URL url = new URL(urlStr);
			conn = (HttpURLConnection) url.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("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
			OutputStream out = new DataOutputStream(conn.getOutputStream());
			// text
			if (textMap != null) {
				StringBuffer strBuf = new StringBuffer();
				Iterator iter = textMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
					strBuf.append("Content-Disposition:form-data;name=\"" + inputName + "\"\r\n\r\n");
					strBuf.append(inputValue);
				}
				out.write(strBuf.toString().getBytes());
			}
			// file
			if (fileMap != null) {
				Iterator iter = fileMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					String inputName = (String) entry.getKey();
					MultipartFile inputValue = (MultipartFile) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					String filename = inputValue.getOriginalFilename();

					// 没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
					String contentType = inputValue.getContentType();

					StringBuffer strBuf = new StringBuffer();
					strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
					strBuf.append("Content-Disposition:form-data;name=\"" + inputName + "\";filename=\"" + filename
							+ "\"\r\n");
					strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
					out.write(strBuf.toString().getBytes());
					InputStream in = inputValue.getInputStream();
					int bytes = 0;
					byte[] bufferOut = new byte[1024];
					while ((bytes = in.read(bufferOut)) != -1) {
						out.write(bufferOut, 0, bytes);
					}
					in.close();
				}
			}
			byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
			out.write(endData);
			out.flush();
			out.close();
			// 读取返回数据

			ByteArrayOutputStream bStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = -1;
			while ((len = conn.getInputStream().read(buffer)) != -1) {
				bStream.write(buffer, 0, len);
			}
			jsonObject = JSONObject.parseObject(new String(bStream.toByteArray(), "UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
		return jsonObject;
	}

}



所属网站分类: 技术文章 > 博客

作者:小胖子爱java

链接:http://www.javaheidong.com/blog/article/852/a80cde0622d1e720880d/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

17 0
收藏该文
已收藏

评论内容:(最多支持255个字符)