美文网首页
okhttp 上传文件

okhttp 上传文件

作者: 年少懵懂丶流年梦 | 来源:发表于2018-04-24 08:30 被阅读4130次

    compile 'com.squareup.okhttp3:okhttp:3.2.0'

    import okhttp3.*
    
    /**
     * 
     */
    class ClientUploadUtils {
    
        static ResponseBody upload(String url, String filePath, String fileName) throws Exception {
            OkHttpClient client = new OkHttpClient()
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", fileName,
                            RequestBody.create(MediaType.parse("multipart/form-data"), new File(filePath)))
                    .build()
    
            Request request = new Request.Builder()
                    .header("Authorization", "Client-ID " + UUID.randomUUID())
                    .url(url)
                    .post(requestBody)
                    .build()
    
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response)
    
            return response.body()
        }
    
    
        static void main(String[] args) throws IOException {
            try {
                String fileName = "com.jdsoft.biz.test.zip"
                String filePath = "D:\\ExtJsTools\\Sencha\\Cmd\\repo\\pkgs\\test.zip"
                String url = "http://localhost:9990/upload_app_package"
                System.out.println(upload(url, filePath, fileName).string())
            } catch (Exception e) {
                e.printStackTrace()
            }
        }
    
    }
    

    相关文章

      网友评论

          本文标题:okhttp 上传文件

          本文链接:https://www.haomeiwen.com/subject/ygddlftx.html