2016-07-18 56 views
1

我从来没有对Jsoup工作之前,现在我有一个项目,其中家伙用JSoup lib和我需要做一些重构,使同样的工作,但与retrofit2 ...转换Jsoup请求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); 
} 

但仍然请求失败...

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

回答

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