httpclient如何一起上传内容和图片

简介: httpclient如何一起上传内容和图片

以文件的形式传参

/**
     * 通过拼接的方式构造请求内容,实现参数传输以及文件传输
     * 
     * @param actionUrl 访问的服务器URL
     * @param params 普通参数
     * @param files 文件参数
     * @return
     * @throws IOException
     */
    public static void post(String actionUrl, Map<String, String> params, Map<String, File> files) throws IOException
    {
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";
        URL uri = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        conn.setReadTimeout(5 * 1000); // 缓存的最长时间
        conn.setDoInput(true);// 允许输入
        conn.setDoOutput(true);// 允许输出
        conn.setUseCaches(false); // 不允许使用缓存
        conn.setRequestMethod("POST");
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
        // 首先组拼文本类型的参数
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet())
        {
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            sb.append(LINEND);
            sb.append(entry.getValue());
            sb.append(LINEND);
        }
        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());
        InputStream in = null;
        // 发送文件数据
        if (files != null)
        {
            for (Map.Entry<String, File> file : files.entrySet())
            {
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                // name是post中传参的键 filename是文件的名称
                sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getKey() + "\"" + LINEND);
                sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
                sb1.append(LINEND);
                outStream.write(sb1.toString().getBytes());
                InputStream is = new FileInputStream(file.getValue());
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1)
                {
                    outStream.write(buffer, 0, len);
                }
                is.close();
                outStream.write(LINEND.getBytes());
            }
            // 请求结束标志
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
            outStream.write(end_data);
            outStream.flush();
            // 得到响应码
            int res = conn.getResponseCode();
            if (res == 200)
            {
                in = conn.getInputStream();
                int ch;
                StringBuilder sb2 = new StringBuilder();
                while ((ch = in.read()) != -1)
                {
                    sb2.append((char) ch);
                }
            }
            outStream.close();
            conn.disconnect();
        }
        // return in.toString();
    }
以数据流的形式传参
public static String postFile(String actionUrl, Map<String, String> params, Map<String, byte[]> files)
            throws Exception
    {
        StringBuilder sb2 = null;
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";
        URL uri = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        conn.setReadTimeout(6 * 1000); // 缓存的最长时间
        conn.setDoInput(true);// 允许输入
        conn.setDoOutput(true);// 允许输出
        conn.setUseCaches(false); // 不允许使用缓存
        conn.setRequestMethod("POST");
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
        // 首先组拼文本类型的参数
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet())
        {
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            sb.append(LINEND);
            sb.append(entry.getValue());
            sb.append(LINEND);
        }
        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());
        InputStream in = null;
        // 发送文件数据
        if (files != null)
        {
            for (Map.Entry<String, byte[]> file : files.entrySet())
            {
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                sb1.append("Content-Disposition: form-data; name=\"pic\"; filename=\"" + file.getKey() + "\"" + LINEND);
                sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
                sb1.append(LINEND);
                outStream.write(sb1.toString().getBytes());
                // InputStream is = new FileInputStream(file.getValue());
                // byte[] buffer = new byte[1024];
                // int len = 0;
                // while ((len = is.read(buffer)) != -1)
                // {
                // outStream.write(buffer, 0, len);
                // }
                // is.close();
                outStream.write(file.getValue());
                outStream.write(LINEND.getBytes());
            }
            // 请求结束标志
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
            outStream.write(end_data);
            outStream.flush();
            // 得到响应码
            int res = conn.getResponseCode();
            if (res == 200)
            {
                in = conn.getInputStream();
                int ch;
                sb2 = new StringBuilder();
                while ((ch = in.read()) != -1)
                {
                    sb2.append((char) ch);
                }
                System.out.println(sb2.toString());
            }
            outStream.close();
            conn.disconnect();
            // 解析服务器返回来的数据
            return ParseJson.getEditMadIconResult(sb2.toString());
        }
        else
        {
            return "Update icon Fail";
        }
        // return in.toString();
    }
用httpUrlConnection并结合开源包能实现发图片微博。
代码如下:
  public String uploadStatus(String token, String tokenSecret, File aFile, String status, String urlPath) {  
     DefaultOAuthConsumer  httpOAuthConsumer = new DefaultOAuthConsumer(OAuthInfo.consumerKey_Sina,OAuthInfo.consumerSecret_Sina);  
        httpOAuthConsumer.setTokenWithSecret(token,tokenSecret);  
        String result = null;  
        try {  
            URL url = new URL(urlPath);
            HttpURLConnection request = (HttpURLConnection) url.openConnection();  
            request.setDoOutput(true);  
            request.setRequestMethod("POST");  
            HttpParameters para = new HttpParameters();  
            para.put("status", URLEncoder.encode(status,"utf-8").replaceAll("\\+", "%20"));  
            String boundary = "---------------------------37531613912423";  
            String content = "--"+boundary+ "\nContent-Disposition: form-data; name=\"status\"\n\n";  
            String pic = "\n--"+boundary+"\nContent-Disposition: form-data; name=\"pic\"; filename=\"image.jpg\"\nContent-Type: image/jpeg\n\n";  
            byte[] end_data = ("\n--" + boundary + "--\n").getBytes();  
            FileInputStream stream = new FileInputStream(aFile);  
            byte[] file = new byte[(int) aFile.length()];  
            stream.read(file);  
            request.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary); //设置表单类型和分隔符    
            request.setRequestProperty("Content-Length", String.valueOf(content.getBytes().length + status.getBytes().length + pic.getBytes().length + aFile.length() + end_data.length)); //设置内容长度    
            httpOAuthConsumer.setAdditionalParameters(para);  
            httpOAuthConsumer.sign(request);
            OutputStream ot = request.getOutputStream();  
            ot.write(content.getBytes());  
            ot.write(status.getBytes());  
            ot.write(pic.getBytes());  
            ot.write(file);  
            ot.write(end_data);  
            ot.flush();  
            ot.close();  
            request.connect();  
           if( request.getResponseCode() == 200)
            result = request.getResponseMessage();
        } catch (FileNotFoundException e1) {  
            e1.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } catch (OAuthMessageSignerException e) {  
            e.printStackTrace();  
        } catch (OAuthExpectationFailedException e) {  
            e.printStackTrace();  
        } catch (OAuthCommunicationException e) {  
            e.printStackTrace();  
        }  
        return result;  
    }
目录
打赏
0
3
3
0
84
分享
相关文章
|
10月前
【微信公众平台对接】有关【上传图文消息内的图片获取URL】调用示例
【微信公众平台对接】有关【上传图文消息内的图片获取URL】调用示例
219 0
文件上传 图片上传 客户端图片上传到服务器
文件上传 图片上传 客户端图片上传到服务器
UEditor自定义图片/文件上传路径与回显
UEditor自定义图片/文件上传路径与回显
677 0
HTML5 图片上传预览(调用摄像头、文件)demo效果示例(整理)
HTML5 图片上传预览(调用摄像头、文件)demo效果示例(整理)
上传图片(最多可以上传5张图片)demo效果示例(整理)
上传图片(最多可以上传5张图片)demo效果示例(整理)
后端处理图片的上传和下载
后端处理图片的上传和下载
229 0
实现手动上传表单数据+图片文件
在很多项目中都会有上传数据+图片的需求,我最近在项目中负责活动发布的板块,需要几个表单数据加两个图片和一个图片数组,我看到产品需求后头就很大,我之前没有做过相关的业务,所以这几天一直在尝试,看到接口文档我内心已经崩了。
184 1
实现手动上传表单数据+图片文件
C#post请求上传图片文件中的总结
使用HttpWebRequest发起请求拼接url以及请求头请求体数据进行数据上传。
665 0
C#post请求上传图片文件中的总结
SpringBoot:上传单个图片,上传图片压缩包,读取本地磁盘图片
SpringBoot:上传单个图片,上传图片压缩包,读取本地磁盘图片
634 0