retrofit 라이브러리를 사용하는 방법을 이해하려고 노력 중이므로 Android 프로젝트와 간단한 PHP 스크립트를 만들었습니다. 내 index.php 파일 위치는 xampp의 htdocs 디렉토리입니다.
여기 내 PHP 스크립트가 있습니다. 스크립트가 실행될 때 문자열을 반환하고 싶습니다.
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php
echo "Success";
?>
</body>
</html>
안드로이드 부분에서 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를 사용해 보았는데 결과는 동일했습니다. 나는 ""를 얻었다
@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);
나는 그것을 스스로 알아 냈다. 문제는 Call 클래스 ( Call<String>
)의 유형으로 String을 사용했다는 것 입니다. 대신을 사용하는 것이 더 Call<ResponseBody>
좋으므로 다음과 같이됩니다.
서비스
@GET("/w/api.php")
Call<ResponseBody> test(@QueryMap Map<String, String> argsMap);
요청하다
Call<ResponseBody> response = dataSyncApi.test(args);
response.enqueue(callback);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다