码迷,mamicode.com
首页 > 编程语言 > 详细

java okhttp 发送图片

时间:2017-08-14 09:58:29      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:nbsp   tran   add   ret   rtb   post   creat   demo   eth   

@RequestMapping(value="/demo2", method=RequestMethod.POST)
    @ResponseBody
    public String demo2(String fileName, MultipartFile myfile, HttpServletRequest request) throws IllegalStateException, IOException{
        
        
        String path = request.getServletContext().getRealPath("files");
        path += "/" + myfile.getOriginalFilename();
        File file = new File(path);
        myfile.transferTo(file);
         OkHttpClient client = new OkHttpClient();
            MediaType MEDIA_TYPE_TEXT = MediaType.parse("image/png");
            
            RequestBody requestBody = new MultipartBuilder()
                    .type(MultipartBuilder.FORM)
                    .addFormDataPart("title","测试图片")
                    .addFormDataPart("file",fileName, RequestBody.create(MEDIA_TYPE_TEXT, new File(path)))
                    .build();
            Request request1 = new Request.Builder()
                    .url("http://192.168.1.139:8080/a/upload/upload")
                    .post(requestBody)
                    .build();
            Response response = client.newCall(request1).execute();
            if (!response.isSuccessful()) {
                throw new IOException("服务器端错误: " + response);
            }
         
           /* System.out.println(response.body().string());*/
            System.out.println(fileName+" - 上传成功");
            return "success";
           }            

 依赖的jar包:http://files.cnblogs.com/files/fengwenzhee/okhttp.rar

java okhttp 发送图片

标签:nbsp   tran   add   ret   rtb   post   creat   demo   eth   

原文地址:http://www.cnblogs.com/fengwenzhee/p/7355887.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!