我們可以使用Facebook的圖形API與多部分上傳照片。 我使用改裝庫進行網絡呼叫
public interface ApiInterface {
@Multipart
@POST("/{id}/photos")
Call<UserModelResponse> uploadPhoto(@Part MultipartBody.Part image, @Path("id")String pageId, @Query("access_token") String token);
}
可以上傳多張圖片
public class ApiCall {
private ApiInterface apiService;
private Context context;
public ApiCall(Context context) {
this.context = context;
}
public ApiInterface getRetroFitService() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Gson gson = new GsonBuilder().create();
Retrofit builder = new Retrofit.Builder()
.baseUrl("https://graph.facebook.com")
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
apiService = builder.create(ApiInterface.class);
return apiService;
}
public void uploadImageToFBPage(String pageId, ArrayList<Parcelable> path) throws IOException {
for (Parcelable parcelable : path) {
MultipartBody.Part body = prepareFilePart("source", (Uri) parcelable);
SharedPreferences sharedPreferences = context.getSharedPreferences(PREFERENCE, Context.MODE_PRIVATE);
String token = sharedPreferences.getString("token", "");
Call<UserModelResponse> call = apiService.uploadPhoto(body, pageId, token);
call.enqueue(new Callback<UserModelResponse>() {
@Override
public void onResponse
(Call<UserModelResponse> call, Response<UserModelResponse> response) {
if (response.errorBody() == null) {
Toast.makeText(context, "Image upload Success", Toast.LENGTH_SHORT).show();
} else {
onFailure(call, new Exception());
}
}
@Override
public void onFailure(Call<UserModelResponse> call, Throwable t) {
Toast.makeText(context, "Image upload Fail", Toast.LENGTH_SHORT).show();
}
});
}
}
@NonNull
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(context, fileUri);
// create RequestBody instance from file
RequestBody requestFile = RequestBody.create(MediaType.parse(context.getContentResolver().getType(fileUri)), file);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
}
PLZ添加日誌.... – 2011-04-27 09:34:28
ndroid.app.ActivityThread.main(ActivityThread.java:4363) 04-27 15:05:49.716:ERROR/AndroidRuntime(2595):at java.lang.reflect.Method.invokeNative(Native Method) 04-27 15:05:49.716:ERROR/AndroidRuntime(2595):at java。 lang.reflect.Method.invoke(Method.java:521) 04-27 15:05:49.716:ERROR/AndroidRuntime(2595):at com.android.internal.os.ZygoteInit $ Meth odAndArgsCaller.run(ZygoteInit.java:860) – Rajan 2011-04-27 09:42:18
你使用的是Facebook API ..? – 2011-04-27 09:45:00