[英]Retrofit 2 response body contents only “<html>” string
我試圖了解如何使用改造庫,因此我創建了一個android項目和一個簡單的php腳本。 我的index.php文件位置是xampp的htdocs目錄。
這是我的PHP腳本,這里我只想在執行腳本時返回一個字符串
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php
echo "Success";
?>
</body>
</html>
在Android部分,我想發送GET請求
@GET("/")
Call<String> test();
我在這里發送回復並進行必要的准備
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.43.169:80/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
IDataSyncApi dataSyncApi = retrofit.create(IDataSyncApi.class);
Callback<String> callback = new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
String responseStr = gson.fromJson(response.body().toString(), String.class);
Log.d("RESPONSE", responseStr);
}
@Override
public void onFailure(Call<String> call, Throwable t) {
}
};
Call<String> response = dataSyncApi.test();
response.enqueue(callback);
問題是Response的主體始終等於“ <html>”。 我究竟做錯了什么?
更新1
我嘗試使用Wikipedia公共API而不是我的API,結果是相同的。 我有 ””
@GET("/w/api.php")
Call<String> test(@QueryMap Map<String, String> argsMap);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://en.wikipedia.org/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
Map<String, String> args = new HashMap<String, String>();
args.put("action", "query");
args.put("meta", "siteinfo");
args.put("siprop", "namespaces");
Call<String> response = dataSyncApi.test(args);
response.enqueue(callback);
我自己弄清楚了。 問題是我將String用作Call類的類型( Call<String>
)。 相反,最好使用Call<ResponseBody>
,因此如下所示:
服務
@GET("/w/api.php")
Call<ResponseBody> test(@QueryMap Map<String, String> argsMap);
提出要求
Call<ResponseBody> response = dataSyncApi.test(args);
response.enqueue(callback);
您可以使用ResponseBody類型。 如下所示:
@Multipart
@POST("/android_upload_file/uploadfile.php")
Call<ResponseBody> upload(@Part("fileName") String des, @Part("file\"; filename=\"1.txt\"")RequestBody file);
您已經在Response<String> response
中將響應作為字符串包含了。 您嘗試使用gson反序列化它,它用於jsons而不是html。
如果仍然無法正常工作,請嘗試使用HttpLoggingInterceptor記錄響應。
您確定要請求正確的PHP文檔嗎? 是XAMPP緩存了文件還是提供了另一個文件(如index.html)?
或者,我將更改PHP文件以使用JSON進行響應,並在Retrofit調用中添加requestHeader以接受JSON(或HTML,具體取決於您的期望)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.