1

I was never work with Jsoup before, and now I have a project, where guys were using JSoup lib, and I need to do some refactoring and make same work but with retrofit2...

I stuck with converting request that send image file. Here is original JSoup request:

    Connection.Response result = Jsoup.connect(apiURL + "sendImg/")
                                .method(Connection.Method.POST)
                                .header("Token", XCSRFToken)
                                .data("source", currentImage.getMD5().concat(".jpg"), 
                                       new FileInputStream(bitmapURI.getPath()))
                                .execute();

here is what i try to do with retrofit:

@Multipart
    @POST("sendImg/")
    Call<CbSendImage> sendImage(@Header("Token") String token, @Part MultipartBody.Part file);

public void sendImage(File file) {
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body =
        MultipartBody.Part.createFormData("source",
                        currentImage.getMD5().concat(".jpg"), requestFile);
        mSendImageCall = mServerApi.sendImage(getToken(), body);
        mSendImageCall.enqueue(sendImageCallback);
}

but request still failed...

Any ideas how convert that request correct? Thanks!

Stan Malcolm
  • 2,740
  • 5
  • 32
  • 53

1 Answers1

3

You can create your own ConverterFactory and use JSOUP in it.

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(HttpUrl.parse("https://www.x.x/x/"))
            .addConverterFactory(PageAdapter.FACTORY)
            .build();

static final class PageAdapter implements Converter<ResponseBody, SecondClass.Page> {
    static final Converter.Factory FACTORY = new Converter.Factory() {
        @Override
        public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
            if (type == SecondClass.Page.class) return new SecondClass.PageAdapter();
            return null;
        }
    };

    @Override
    public SecondClass.Page convert(ResponseBody responseBody) throws IOException {
        Document document = Jsoup.parse(responseBody.string());
        Element value = document.select("script").get(1);
        String content = value.html();
        return new SecondClass.Page(content);
    }
}

For more information or complete example, you can refer to this link

Harish Gyanani
  • 1,366
  • 2
  • 22
  • 43