依赖:
compile 'com.squareup.retrofit2:converter-gson:2.0.1'compile 'com.squareup.retrofit2:retrofit:2.0.1'
接口:
public interface setData { @Multipart @POST() Call<ResponseBody> upload(@Url String url, @Query("uid") int uid, @Part MultipartBody.Part file); }主Activity:
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.zhaoapi.cn/").addConverterFactory(GsonConverterFactory.create()) //.client(okHttpClient) .build(); System.out.println("*************"); Head head = retrofit.create(Head.class); File file = new File(Environment.getExternalStorageDirectory(),"b.jpg"); // 创建 RequestBody,用于封装构建RequestBody RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); // MultipartBody.Part 和后端约定好Key,这里的partName是用image MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile); Call<ResponseBody> sethead = head.upload("https://www.zhaoapi.cn/file/upload", 86, body); sethead.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { final String string = response.body().string(); System.out.println("****+++成功+++****"+string); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, string+"", Toast.LENGTH_SHORT).show(); } }); } catch (IOException e) { e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, final Throwable t) { System.out.println("***--失败--***" + t.toString()); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, t.toString()+"", Toast.LENGTH_SHORT).show(); } }); } });