我以前从未使用过 Jsoup,现在我有一个项目,人们正在使用 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);
}
但是请求还是失败了...
任何想法如何正确转换该请求?谢谢!
最佳答案
您可以创建自己的 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
关于android - 将 Jsoup 请求转换为 retrofit2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38437208/