我正在开发一个Android应用程序。在这里,我需要更新服务器上的图像。 Web Service可以在此处接受3个字段。 1.图像类型(String) 2.文件(文件) 3. user_id(String)
那么如何使用android中的某些API来实现此功能。到目前为止,我使用Volley进行服务器通信,但我被困在这里。我试图通过使用HttpClient来实现这个功能,但这不起作用而且不够用。
答案 0 :(得分:1)
对多部分内容使用改造。它闪电般快。
在APInterface中写下以下内容,在字符串RequestBody中添加照片MultiPart正文和所有其他参数
@Multipart
@POST("MethodName")
Call<Response> updateUser(@Part MultipartBody.Part photo,
@Part("string") RequestBody string);
ApiClient中的这些行
public static OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build();
public static Retrofit getClient() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("url").addConverterFactory(GsonConverterFactory.create()).client(okHttpClient).build();
return retrofit;
}
在您的活动中使用这些Multipart改造技术将文件发送到服务器。
//path is the file path
File image = new File("" + (String) path);
RequestBody requestFile =
RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA), image);
MultipartBody.Part fileImage = null;
if (requestFile.contentLength() != 0)
fileImage = MultipartBody.Part.createFormData("file", image.getName(), requestFile);
并使用改装调用发送该文件它将起作用。