我正在使用retrofit2 - httpok3以便与Laravel 5.6服务器通信。
我正在尝试" GET"使用http GET方法的数据帐户。
这是我用来建立android连接的Java类:
界面SvcApi :
@GET("api/me")
public Call<JSONObject> getMe(@Query("device_id") String device_id);
服务类
public class Svc {
private static SvcApi giftSvc_;
public static synchronized SvcApi initAuth(Context c) {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
DatabaseManager db = new DatabaseManager(c);
if (db.ExistsUser()) {
final String token = db.findUser().getToken();
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + token)
.build();
});
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Defaultdata.DEFAULT_IP + ":" + Defaultdata.DEFAULT_PORT + "/")
.client(httpClient.build())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
giftSvc_ = retrofit.create(SvcApi.class);
return giftSvc_;
} else {
return null;
}
}
这是我的Activity类中实现的方法,以便获取数据:
private void changeActivityTest(){
svcAth = Svc.initAuth(getApplicationContext());
Call<JSONObject> call = svcAth.getMe(Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID));
call.enqueue(new Callback<JSONObject>() {
@Override
public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {
final JSONObject user = response.body();
final Response<JSONObject> responsefinal = response;
Log.e("responsefinal code", responsefinal.code() + "");
Log.e("responsefinal message", responsefinal.message());
Log.e("responsefinal headers", responsefinal.headers().toString());
Log.e("responsef isSuccessful", responsefinal.isSuccessful() + "");
Log.e("responsefinal raw", responsefinal.raw().toString());
Log.e("responsefinal body", responsefinal.body().toString());
if (response.isSuccessful()) {
runOnUiThread(new Runnable() {
@Override
public void run() {
System.out.println("Success, getMeTest Response body = " + user.toString());
if(responsefinal.code() == 400){
}else if(responsefinal.code() == 201 || responsefinal.code() == 200){
Log.e("response", user.toString());
Log.e("e", responsefinal.toString());
}
}
});
} else {
try {
Log.e("error code :",response.toString() + "");
Log.e("error code :",response.code() + "");
Log.e("error:",response.message());
Log.v("Error ", response.errorBody().string());
}catch(Exception e){
e.printStackTrace();
}
if(responsefinal.code() == 500|| responsefinal.code() == 503){
Toast.makeText(getApplicationContext(), "O serviço Voado está indisponível neste momento. Por favor, tente mais tarde.", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onFailure(Call<JSONObject> call, Throwable t) {
t.printStackTrace();
}
});
}
正文是一个空的JSONObject {}
。
这是我的 LogCat :
05-19 18:48:23.268 14659-14659/com.androidsrc.futbolin E/responsefinal code: 200
05-19 18:48:23.268 14659-14659/com.androidsrc.futbolin E/responsefinal message: OK
05-19 18:48:23.268 14659-14659/com.androidsrc.futbolin E/responsefinal headers: Date: Sat, 19 May 2018 21:48:22 GMT
Server: Apache/2.4.18 (Ubuntu)
Vary: Authorization
Cache-Control: no-cache, private
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
Content-Length: 62
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: application/json
05-19 18:48:23.268 14659-14659/com.androidsrc.futbolin E/responsef isSuccessful: true
05-19 18:48:23.268 14659-14659/com.androidsrc.futbolin E/responsefinal raw: Response{protocol=http/1.1, code=200, message=OK, url=http://XXXXXXXXX:5500/api/me?device_id=c4791147feeb7e7e}
05-19 18:48:23.268 14659-14659/com.androidsrc.futbolin E/responsefinal body: {}
最后,这是属于这些通信的版本库:
dependencies {
[...]
implementation 'com.google.code.gson:gson:2.8.0'
implementation 'org.apache:apache:17'
implementation 'com.google.guava:guava:25.0-android'
implementation('com.squareup.retrofit2:retrofit:2.3.0') {
// exclude Retrofit’s OkHttp peer-dependency module and define your own module import
exclude module: 'okhttp'
}
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'io.reactivex:rxandroid:1.2.1'
implementation 'com.squareup.retrofit2:converter-protobuf:2.3.0'
implementation 'com.fasterxml.jackson.core:jackson-core:2.9.4'
[...]
}
与GsonConverterFactory
中的Retrofit.Builder()
相关,我试图删除gson
:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Defaultdata.DEFAULT_IP + ":" + Defaultdata.DEFAULT_PORT + "/")
.client(httpClient.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
还使用了另一个gson
实现:
Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(String.class,
new JsonDeserializer<String>() {
@Override
public String deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
return null;
}
}).create();
所以,使用具有完全相同的参数,标题和端点的Postman,响应是一个JSONObject,如图所示,但是使用这个android实现,正文是空的。
修改
我尝试使用pojo类:
public class user implements Serializable {
long id;
String first_name;
String last_name;
public user(){}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
@Override
public String toString() {
return "user{" +
"id=" + id +
", first_name='" + first_name + '\'' +
", last_name='" + last_name + '\'' +
'}';
}
}
但结果是一样的。所有值都为null:
responsefinal body: user{id=0, first_name='null', last_name='null'}
答案 0 :(得分:2)
啊你试图从响应中获得JSON
但是你正在使用转换器我认为这是不可能的。您需要删除addConverterFactory
或创建POJO
类,并从POJO
获取值。例如:
public class MyClass {
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@SerializedName("user")
private User user;
private class User {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@SerializedName("last_name")
private String lastName;
@SerializedName("id")
private String id;
@SerializedName("first_name")
private String firstName;
}
}
将JSONObject
替换为MyClass
,作为回应,您将能够getUser()
和用户信息。