Http Post请求 接口 传输 File 组合参数 | 接口支持传输语音流

类似于以下方式的请求可参考,以下代码:

Http Post请求 接口 传输 File 组合参数 | 接口支持传输语音流_第1张图片

package com.ctd.cloud.goclouds.usercenter.awscase.controller;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Test;

import java.io.*;

/**
 * @author sunlinan
 * @Description:
 * @date 2019-04-13 20:50
 */
public class UploadHttpClientTest {
    private String url="http://localhost:8080/clouds-api/upload/file3/";
    private String filePath="/Users/sunlinan/Documents/test_file/test.PNG";
    @Test
    public void inputStreamUpload() {
        //创建HttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //构建POST请求
        //1)
        HttpPost post = new HttpPost(url);
        InputStream inputStream = null;
        try {
            //文件路径请换成自己的
            //2)
            inputStream = new FileInputStream(filePath);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            //第一个参数为 相当于 Form表单提交的file框的name值 第二个参数就是我们要发送的InputStream对象了
            //第三个参数是文件名
            //3)
            builder.addBinaryBody("uploadFile", inputStream, ContentType.create("multipart/form-data"), "test.PNG");
            //4)构建请求参数 普通表单项
            StringBody stringBody = new StringBody("{\"accessKeyId\": \"12\",\"assumeRole\": false,\"cloudType\": \"AWS\",\"secretKey\": \"12\"}", ContentType.APPLICATION_JSON);
            builder.addPart("id",stringBody);
            HttpEntity entity = builder.build();
            post.setEntity(entity);
            //发送请求
            HttpResponse response = client.execute(post);
            //获取请求响应码
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode==200){
                entity = response.getEntity();
                if (entity != null) {
                    inputStream = entity.getContent();
                    //转换为字节输入流
                    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, Consts.UTF_8));
                    String body = null;
                    while ((body = br.readLine()) != null) {
                        System.out.println(body);
                    }
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @Test
   public static void fileUpload() {
        //构建HttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //构建POST请求
        HttpPost httpPost = new HttpPost("http://10.10.109.90:8172/asr/speech2Text");
        InputStream inputStream = null;
        try {
            //要上传的文件
            File file = null;
            file = new File("C:\\uploadFile\\eb4c03ed9caa4cdd840d99f4ab96ad3d\\voice\\1111.mp3");
            //构建文件体
            FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA, "1111.mp3");
            StringBody stringBody = new StringBody("12", ContentType.MULTIPART_FORM_DATA);
            HttpEntity httpEntity = MultipartEntityBuilder
                    .create()
                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .addPart("file", fileBody)
                    .addTextBody("appId","sobot")
                    .build();
            httpPost.setEntity(httpEntity);
            //发送请求
            HttpResponse response = client.execute(httpPost);
            httpEntity = response.getEntity();
            if (httpEntity != null) {
                inputStream = httpEntity.getContent();
                //转换为字节输入流
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, Consts.UTF_8));
                String body = null;
                while ((body = br.readLine()) != null) {
                    System.out.println(body);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

 

 

接口可以支持接收语音流的方式

/**
	 * 语音转文字接口
	 * @param request
	 * @param response
	 * @param fileUrl
	 * @param uid
	 * @param robotFlag
	 */
	@RequestMapping(value="speech2Text")
	public void speech2Text(HttpServletRequest request ,HttpServletResponse response,
								 String fileUrl,String uid,Integer robotFlag , String base64) {
		Long beginTime = System.currentTimeMillis();
		//测试环境url
		String url = "http://10.10.109.90:8172/asr/speech2Text";
		Map params = new HashMap<>();
		Map map = new HashMap();
		User user = UserCache.getUser(uid);
		String companyId = "fa80cd602dde489eb34207510aff607a";
		if(user != null && StringUtil.isNotNull(user.getPid())){
			companyId = user.getPid();
		}
		try{
			/*MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			InputStream speech = multipartRequest.getInputStream();
			long length = 0;
			while (length == 0) {
				length = speech.available();
			}*/


			String fileName = UUIDUtil.getUUID() + ".mp3";
			String filePath = "chatres/"+ companyId + "/voice/" +uid+"/"+ fileName;

			if(StringUtil.isNotNull(base64)){
				byte[] bytes = Base64.decodeBase64(base64.split(",")[1]);
				for (int i = 0; i < bytes.length; ++i) {
					if (bytes[i] < 0) {// 调整异常数据
						bytes[i] += 256;
					}
				}
				InputStream inputStream = new ByteArrayInputStream(bytes);
				OSSUtil.uploadFile(filePath,inputStream, bytes.length, fileName);
			}else{
				//OSSUtil.uploadFile(filePath,speech, length, fileName);
			}

			if(StringUtil.isNull(fileUrl)){
				fileUrl = ConfigUtil.getUrlPrefix()+filePath;
			}

			params.put("fileUrl",fileUrl);
			params.put("appId","sobot");
			logger.info("bainian_speech_voice_url"+ConfigUtil.getUrlPrefix()+filePath +" speech2Text_post_param :"+fileUrl);
			String result = HttpUtil.sendPost(url,params);
			JSONObject resultStr = null;
			if(StringUtil.isNotNull(result)){
				resultStr = JSONObject.parseObject(result);
			}

			if(resultStr != null && resultStr.getString("code").equals("000000")){
				map.put("code","000000");
				map.put("msg","语音转文字成功!");
				map.put("result",resultStr.getString("result"));
			}else{
				map.put("code","000001");
				map.put("msg","语音转文字接口异常!");
			}
			logger.info("speech2Text:"+uid+" fileUrl:"+fileUrl+ " :result"+result +" :time"+ (System.currentTimeMillis()-beginTime));
		}catch (Exception e){
			map.put("code","000001");
			map.put("msg","语音转文字接口异常!!");
			e.printStackTrace();
		}
		new ResponseUtil().doResponse(request,response,map);
	}

 

 

你可能感兴趣的:(------【Java】,●编程语言)