读取http链接资源并上传到远程服务器

业务场景:有一段http音频资源,需要将这段音频上传到第三方服务器,但是其中有一个点,读取资源后要么不再服务器生成一份,要么生成后删除。

因此采用FIle的一种创建临时文件的技术方案进行读取后,这样就不会再服务器上生成。

下面是亲测代码,无须更改可以直接使用,

笔者调用第三方,第三方的content-type 严格要求是audio/mp3格式,

第一个方法是将http的资源地址读取转成url,第二个方法是将file上传到第三方服务器

上业务代码:

方法audioNo参数为文件的名称,audioUrl参数是文件的远程http地址

import java.io.*;
import java.net.URL;
import java.util.Objects;

public static File readUrl(String audioNo,String audioUrl) {
            OutputStream outputStream=null;
            InputStream inputStream=null;
            File file=null;
            try {
                URL url = new URL(audioUrl);
                // 打开连接并读取数据
                inputStream = url.openStream();
                File tempFile=File.createTempFile("temp",".mp3");
                outputStream=new FileOutputStream(tempFile);
                int read = 0;
                byte[] bytes = new byte[1024];
                while ((read = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
                inputStream.close();
                outputStream.close();
                file = new File(tempFile.getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(Objects.nonNull(inputStream)){
                        inputStream.close();
                    }
                    if(Objects.nonNull(outputStream)){
                        outputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return file;
}

上传file到远程服务器

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Set;

public static String postFile(String host,String uri, Map params, File file, String fileName, String token) {
        String responseBody = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            //设置编码格式
            builder.setCharset(Charset.forName("utf-8"));
            builder.setContentType(ContentType.MULTIPART_FORM_DATA);
            //File audioFile=covertInputStreamToFile(file.getInputStream());
            log.info("音频文件大小:{}",file.length());
            builder.addBinaryBody("file", file, ContentType.create("audio/mp3"), fileName );
            //builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            Set> entries = params.entrySet();
            for(Map.Entry param:entries){
                builder.addTextBody(param.getKey(),param.getValue().toString());
            }
            //构建请求实体
            HttpEntity entity = builder.build();
            //  创建Post方式请求
            HttpPost httpPost = new HttpPost(host+uri);
            httpPost.addHeader("Accept-Encoding", "gzip");
            httpPost.addHeader("Authorization","Bearer "+token);
            httpPost.addHeader("Accept","*/*");
            httpPost.addHeader("Connection","keep-alive");
            //httpPost.addHeader("Host","10.1.29.188:5000");
            httpPost.setEntity(entity);
            //发送请求
            response = httpClient.execute(httpPost);
            log.info("上传音频文件返回:{}",JSONObject.toJSONString(response));
            //状态码
            int statusCode = response.getStatusLine().getStatusCode();
            String reasonPhrase = response.getStatusLine().getReasonPhrase();
            //data
            responseBody = EntityUtils.toString(response.getEntity(),"UTF-8");
            log.info("结果:{}",responseBody);
            //}
        } catch (IOException e) {
            e.printStackTrace();
        }finally {//处理结束后关闭httpclient的链接
            try {
                if(httpClient != null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseBody;
    }

你可能感兴趣的:(文件上传,服务器,http,java)