Programing

Android에서 GSON 또는 다른 라이브러리를 사용하지 않고 개조를 사용하여 문자열로 응답을 얻는 방법

lottogame 2020. 8. 26. 08:22
반응형

Android에서 GSON 또는 다른 라이브러리를 사용하지 않고 개조를 사용하여 문자열로 응답을 얻는 방법


이 질문에 이미 답변이 있습니다.

다음 API에서 응답을 얻으려고합니다.

https://api.github.com/users/username

하지만을 String사용하여 String.NET을 구문 분석하고 가져올 수 있도록 응답을 얻는 방법을 모르겠습니다 JSONObject.

사용 된 개조 버전 :

개조 : 2.0.0-beta1

나는 지금까지 이것을 시도했다 :

public interface GitHubService {
        @GET("/users/{user}")
        public String listRepos(@Path("user") String user,Callback<String> callback);
    }

검색 :

GitHubService service = retrofit.create(GitHubService.class);
        service.listRepos("username", new Callback<String>() {
            @Override
            public void onResponse(Response response) {
                System.out.println(response.toString());
            }

            @Override
            public void onFailure(Throwable t) {

            }
        });

예외:

Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for class java.lang.String. Tried:
    * retrofit.ExecutorCallAdapterFactory
            at retrofit.Utils.resolveCallAdapter(Utils.java:67)
            at retrofit.MethodHandler.createCallAdapter(MethodHandler.java:49)

어떤 도움이라도 정말 감사하겠습니다.


** 업데이트 ** String아래의 원래 답변보다 덜 의식적인 응답 을 허용하는 스칼라 변환기가 개조에 추가되었습니다 .

예제 인터페이스-

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

ScalarsConverterFactory개조 빌더에을 추가하십시오 . 참고 :ScalarsConverterFactory 및 다른 팩토리를 사용하는 경우 먼저 스칼라 팩토리를 추가하십시오.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

gradle 파일에 스칼라 변환기도 포함해야합니다.

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- 원래 답변 (여전히 작동하며 더 많은 코드) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

참고URL : https://stackoverflow.com/questions/32617770/how-to-get-response-as-string-using-retrofit-without-using-gson-or-any-other-lib

반응형