【发布时间】:2018-07-12 13:05:46
【问题描述】:
【问题讨论】:
-
查看本教程futurestud.io/tutorials/…,它可以帮助您使用 Retrofit 将文件发送到服务器
标签: android
【问题讨论】:
标签: android
试试这个代码..
将以下依赖添加到应用级 gradle 文件中..
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
然后定义改造对象..
public class ApiClient {
private final static String BASE_URL = "https://api.github.com";
public static ApiClient apiClient;
private Retrofit retrofit = null;
public static ApiClient getInstance() {
if (apiClient == null) {
apiClient = new ApiClient();
}
return apiClient;
}
//private static Retrofit storeRetrofit = null;
public Retrofit getClient() {
return getClient(null);
}
private Retrofit getClient(final Context context) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.readTimeout(60, TimeUnit.SECONDS);
client.writeTimeout(60, TimeUnit.SECONDS);
client.connectTimeout(60, TimeUnit.SECONDS);
client.addInterceptor(interceptor);
client.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
return chain.proceed(request);
}
});
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
制作api接口..
public interface ApiInterface {
@Multipart
@POST("/signup/")
Call<UserResponseVo> registerUser(@PartMap Map<String, RequestBody> map);
}
和 api 调用到活动中..
private void uploadImage() {
ApiInterface apiInterface= ApiClient.getInstance().getClient().create(ApiInterface.class);
file=new File(mAttachmentFilePath);
RequestBody mFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("profile_pic", file.getName(), mFile);
RequestBody userObjectId = RequestBody.create(MediaType.parse("text"), "HZucg1m6Gz");
Call<UserProfileResponse> userProfileResponseCall=apiInterface.uploadImage(fileToUpload,userObjectId);
showProgress();
userProfileResponseCall.enqueue(new Callback<UserProfileResponse>() {
@Override
public void onResponse(Call<UserProfileResponse> call, Response<UserProfileResponse> response) {
if (response!=null && response.body()!=null && response.isSuccessful()){
closeProgress();
Toast.makeText(getApplicationContext(),response.body().getMsg(),Toast.LENGTH_LONG).show();
Log.d("Response Message::",response.body().getMsg());
Glide.with(MainActivity.this).load(response.body().getAvatarUrl()).into(mIvServerImage);
}
}
@Override
public void onFailure(Call<UserProfileResponse> call, Throwable t) {
closeProgress();
Log.d("Error::",t.getMessage());
}
});
}
我希望您知道如何打开图库并获取选定的图像路径。 如果您在 marshallow 设备上运行应用程序,则添加权限模型。
【讨论】: