Retrofit을 사용하여 API를 누른 후 사용자 데이터를 표시하려고합니다. 내 API 응답은 다음과 같습니다.
{
"password":"111222333",
"name":"test name",
"email":"[email protected]",
"username":"test1",
"customer_id":"201060",
"phone":"0196789"
}
하지만 안타깝게도
"BEGIN_OBJECT가 필요하지만 행 1 열 1 경로 $에서 STRING입니다."오류.
나는 내 json 응답을 보여주기 위해 완전히 붙어 있습니다.
내 User.java 클래스 :
public class User {
@SerializedName("name")
@Expose
private String name;
@SerializedName("email")
@Expose
private String email;
@SerializedName("username")
@Expose
private String username;
@SerializedName("customer_id")
@Expose
private String customerId;
@SerializedName("phone")
@Expose
private String phone;
@SerializedName("password")
@Expose
private String password;
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getUsername() {
return username;
}
public String getCustomerId() {
return customerId;
}
public String getPhone() {
return phone;
}
public String getPassword() {
return password;
}
}
내 로그인 클래스 :
Gson gson = new GsonBuilder().setLenient().create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://us-central1-gmx-notification.cloudfunctions.net/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
all_api = retrofit.create(allApi.class);
private void getUserDetails(String userName,String passWord){
Call<User> call = all_api.getUserDetails(userName,passWord);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if(!response.isSuccessful()){
Log.d(response.body());
}
else{
User user = response.body();
String content = "";
content+= "Name: "+user.getName()+"\n";
content+= "Email: "+user.getEmail()+"\n";
content+= "Customer ID: "+user.getCustomerId()+"\n";
content+= "Phone: "+user.getPhone()+"\n";
Log.d(content);
}
});
}
및 내 개조 API 클래스 :
package com.material.components;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface allApi {
@GET("login")
Call <User> getUserDetails(
@Query("email") String email,
@Query("password") String password
);
}
내가 당신을 때리면 api https://us-central1-gmx-notification.cloudfunctions.net/[email protected]&password=12345678
이 응답을 받았습니다
오류 : 요청을 처리 할 수 없습니다.
따라서 오류가 Object를 예상했지만 문자열이 있다고 말합니다. 그래서 또는 백엔드 측의 오류 또는 요청이 올바르지 않거나 요청에 무언가를 추가하는 것을 잊었습니다 (헤더 또는 다른 것 ...).
모델에없는 문제는 응답에서 기대하는 모델이 아닙니다. OkHttpClient에 인터셉터를 추가하여 확실한 것을 확인하십시오.
이 종속성을 gradle에 추가해야합니다.
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'
다음은 로그에있는 모든 네트워킹 항목을 인쇄하는 API 코드 예제입니다.
public class NetworkManager {
private static RESTAuthService restAuthService;
/*timeout values in seconds*/
private static final int CONNECTION_TIMEOUT = 10;
private static final int WRITE_TIMEOUT = 10;
private static final int READ_TIMEOUT = 10;
static RESTAuthService getRESTAuthService() {
if (restAuthService == null) {
synchronized (NetworkManager.class) {
if (restAuthService == null) {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new RESTInterceptor())
.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(NetworkConfig.BASE_AUTH_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
restAuthService = retrofit.create(RESTAuthService.class);
}
}
}
return restAuthService;
}
private static class RESTInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Buffer buffer = new Buffer();
if (request.body() != null) {
request.body().writeTo(buffer);
}
Log.d("HTTP Request", "Request to " + request.url().toString()
+ "\n" + request.headers().toString()
+ "\n" + buffer.readUtf8());
long t1 = System.nanoTime();
Response response = chain.proceed(request);
long t2 = System.nanoTime();
String msg = response.body().string();
msg = msg.replace("\r", ""); // Note: Messages with '\r' not displayed correctly in logcat
Log.d("HTTP Response", String.format("Response from %s in %.1fms%n\n%s",
response.request().url().toString(), (t2 - t1) / 1e6d, msg));
Log.d("HTTP Response", "Response code = " + response.code());
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), msg))
.build();
}
}
}
MyLogin 클래스는 다음과 같습니다.
public class MuLogin {
/*timeout values in seconds*/
private static final int CONNECTION_TIMEOUT = 10;
private static final int WRITE_TIMEOUT = 10;
private static final int READ_TIMEOUT = 10;
allApi = all_api;
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new RESTInterceptor())
.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://us-central1-gmx-notification.cloudfunctions.net/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
all_api =retrofit.create(allApi.class);
public void getUserDetails(String userName, String passWord) {
Call<User> call = all_api.getUserDetails(userName, passWord);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if (!response.isSuccessful()) {
Log.d(response.body());
} else {
User user = response.body();
String content = "";
content += "Name: " + user.getName() + "\n";
content += "Email: " + user.getEmail() + "\n";
content += "Customer ID: " + user.getCustomerId() + "\n";
content += "Phone: " + user.getPhone() + "\n";
Log.d(content);
}
});
}
}
private static class RESTInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Buffer buffer = new Buffer();
if (request.body() != null) {
request.body().writeTo(buffer);
}
Log.d("HTTP Request", "Request to " + request.url().toString()
+ "\n" + request.headers().toString()
+ "\n" + buffer.readUtf8());
long t1 = System.nanoTime();
Response response = chain.proceed(request);
long t2 = System.nanoTime();
String msg = response.body().string();
msg = msg.replace("\r", ""); // Note: Messages with '\r' not displayed correctly in logcat
Log.d("HTTP Response", String.format("Response from %s in %.1fms%n\n%s",
response.request().url().toString(), (t2 - t1) / 1e6d, msg));
Log.d("HTTP Response", "Response code = " + response.code());
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), msg))
.build();
}
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다