okhttp 上传文件
2018-04-24 本文已影响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()
}
}
}