答案 0 :(得分:0)
尝试此代码。
将下面的代码添加到应用程序级别的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设备上方运行应用,则添加权限模型。