java okhttp 发送图片
Posted 陈扬天
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java okhttp 发送图片相关的知识,希望对你有一定的参考价值。
@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 发送图片的主要内容,如果未能解决你的问题,请参考以下文章
OkHttpOkHttp 上传图片 ( 获取 SD 卡动态权限 | 跳转到相册界面选择图片 | 使用 OkHttp 上传图片文件 )