【问题标题】:Convert Jsoup request to retrofit2将 Jsoup 请求转换为 retrofit2
【发布时间】:2016-11-21 02:09:29
【问题描述】:

我以前从未使用过 Jsoup,现在我有一个项目,人们正在使用 JSoup lib,我需要进行一些重构并进行相同的工作,但要使用 retrofit2...

我坚持转换发送图像文件的请求。这是原始 JSoup 请求:

    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();

这是我尝试做的改造:

@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);
}

但请求仍然失败...

任何想法如何正确转换该请求?谢谢!

【问题讨论】:

    标签: android jsoup retrofit multipartform-data retrofit2


    【解决方案1】:

    您可以创建自己的 ConverterFactory 并在其中使用 JSOUP。

    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);
        }
    }
    

    更多信息或完整示例,可以参考这个link

    【讨论】:

      猜你喜欢
      • 2021-06-30
      • 2018-04-16
      • 1970-01-01
      • 2021-02-06
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      相关资源
      最近更新 更多