java发送HTTP协议文件,最好使用OkHttpClient类来实现,我用了别人封装的一些方法,上传文件有些文件会出现上传失败!
OkHttpClient上传文件代码:
public static boolean uploadFile(String actionUrl,File file,String token) { OkHttpClient client = new OkHttpClient().newBuilder() .build(); MediaType mediaType = MediaType.parse("multipart/form-data"); RequestBody body = RequestBody.create(mediaType, file); Request request = new Request.Builder() .url(actionUrl) .method("POST", body) .addHeader("Authorization", token) .addHeader("Accept", "application/json;odata=verbose") .addHeader("Content-Type", "multipart/form-data") .build(); try { Response response = client.newCall(request).execute(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }