Android POST 使用 Retrofit 调用获取服务器 500 错误
Android POST call getting Server 500 error using Retrofit
这似乎是一个非常简单的问题,但我想不通。我调用的 API 在 Postman 中运行良好,并构成应用程序的 iOS 版本。只是 Android 让我感到不适。咖啡可能不够。我正在使用 Android Studio 进行最新更新。
API 接受长 URL 作为 JSON 主体,returns 接受短 URL 作为字符串。
错误截图:
Android Error Screenshot
POST 调用:
private void getShortURL() {
//Get full url
final String fullURL = Constants.SHARE_BASE_URI + urlParameters;
//Convert URL to JSON formatted data
Map<String,String> data = new HashMap<String,String>();
data.put("URL",fullURL);
String jsonData = new GsonBuilder().create().toJson(data,Map.class);
//Call API and pass in JSON to get Short URL
Call<ResponseBody> getDynamicLinkCall = RetrofitAdapter.getRetroInterface(Constants.BASE_URI).getDynamicLink_String(Constants.getTimestamp(),Constants.APPLICATION,"application/json", jsonData);
getDynamicLinkCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response == null || response.code() != Constants.SUCCESS) {
//Share Short URL
share(response.body().toString());
}
else
{
//If Short URl Failed share long URL
share(fullURL);
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
//If Short URl Failed share long URL
share(fullURL);
}
});
}
RetrofitInterface.java
@POST("URLShortner")
Call<ResponseBody> getDynamicLink_String(@Header("TimeStamp") String timestamp, @Header("Application") String application, @Header("Content-Type") String contentType, @Body String jsonData);
邮递员截图:
Screenshot from Postman showing Body settings
改造适配器代码:
package com.company.appname.util;
import android.content.Context;
import com.company.appname.Constants;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.concurrent.TimeUnit;
import okhttp3.CookieJar;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
public class RetrofitAdapter {
public static OkHttpClient okHttpClient;
public static Context context;
public static RetrofitInterface getRetroInterface(String endPoint){
return createRestAdapter(endPoint).create(RetrofitInterface.class);
}
public static Retrofit createRestAdapter(String endPoint){
boolean isMobileAPI = false;
//Check if the endpoint is the mobile api
if(endPoint.equalsIgnoreCase(Constants.MOBILE_SERVICE_BASE_URI)){
isMobileAPI = true;
}
//Create a rest adapter
return new Retrofit.Builder()
.client(createOkClient(isMobileAPI))
.baseUrl(endPoint)
.addConverterFactory(JacksonConverterFactory.create())
.build();
}
public static OkHttpClient createOkClient(boolean isMobileAPI){
NextModel next = NextModel.getInstance();
if(next.okClient == null || !isMobileAPI) {
//Create ok http Client
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
//Set timeouts
httpClient.readTimeout(Constants.TIMEOUT, TimeUnit.MILLISECONDS);
httpClient.connectTimeout(Constants.TIMEOUT, TimeUnit.MILLISECONDS);
CookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context));
//Add cookieJar to Http Client
httpClient.cookieJar(cookieJar);
//Create OkHttpClient
okHttpClient = httpClient.build();
return okHttpClient;
}else{
//Return already created okclient
return next.okClient;
}
}
public static OkHttpClient getOkClient() {
return okHttpClient;
}
}
我错过了什么?
提前致谢!
好的,我们发现了问题。我们缺少以下代码行:
RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),jsonObject.toString());
此代码在 POST 调用之前进入,而不是 POSTing jsonData,我们 post body 修复了它。希望 Android Studio 给出了某种错误来提示这一点。
完整方法:
private void getShortURL() {
//Get full url
final String fullURL = Constants.SHARE_BASE_URI + urlParams;
//Convert URL to JSON formatted data
Map<String,String> data = new HashMap<String,String>();
data.put("LINK",fullURL);
String jsonData = new GsonBuilder().create().toJson(data,Map.class);
RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonData);
//Call API and pass in JSON to get Short URL
Call<String> getDynamicLinkCall = RetrofitAdapter.getRetroInterface(Constants.BASE_URI).getDynamicLink_String(Constants.getTimestamp(),Constants.APPLICATION,"application/json", body);
getDynamicLinkCall.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (response == null || response.code() != Constants.SUCCESS) {
//Share Short URL
share(response.body().toString());
}
else
{
//If Short URl Failed share long URL
share(fullURL);
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
//If Short URl Failed share long URL
share(fullURL);
}
});
}
RetrofitINterface.java:
@POST("URLShortner")
Call<String> getDynamicLink_String(@Header("TimeStamp") String timestamp, @Header("Application") String application, @Header("Content-Type") String contentType, @Body RequestBody jsonData);
谢谢大家!
这似乎是一个非常简单的问题,但我想不通。我调用的 API 在 Postman 中运行良好,并构成应用程序的 iOS 版本。只是 Android 让我感到不适。咖啡可能不够。我正在使用 Android Studio 进行最新更新。
API 接受长 URL 作为 JSON 主体,returns 接受短 URL 作为字符串。
错误截图:
Android Error Screenshot
POST 调用:
private void getShortURL() {
//Get full url
final String fullURL = Constants.SHARE_BASE_URI + urlParameters;
//Convert URL to JSON formatted data
Map<String,String> data = new HashMap<String,String>();
data.put("URL",fullURL);
String jsonData = new GsonBuilder().create().toJson(data,Map.class);
//Call API and pass in JSON to get Short URL
Call<ResponseBody> getDynamicLinkCall = RetrofitAdapter.getRetroInterface(Constants.BASE_URI).getDynamicLink_String(Constants.getTimestamp(),Constants.APPLICATION,"application/json", jsonData);
getDynamicLinkCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response == null || response.code() != Constants.SUCCESS) {
//Share Short URL
share(response.body().toString());
}
else
{
//If Short URl Failed share long URL
share(fullURL);
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
//If Short URl Failed share long URL
share(fullURL);
}
});
}
RetrofitInterface.java
@POST("URLShortner")
Call<ResponseBody> getDynamicLink_String(@Header("TimeStamp") String timestamp, @Header("Application") String application, @Header("Content-Type") String contentType, @Body String jsonData);
邮递员截图:
Screenshot from Postman showing Body settings
改造适配器代码:
package com.company.appname.util;
import android.content.Context;
import com.company.appname.Constants;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.concurrent.TimeUnit;
import okhttp3.CookieJar;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
public class RetrofitAdapter {
public static OkHttpClient okHttpClient;
public static Context context;
public static RetrofitInterface getRetroInterface(String endPoint){
return createRestAdapter(endPoint).create(RetrofitInterface.class);
}
public static Retrofit createRestAdapter(String endPoint){
boolean isMobileAPI = false;
//Check if the endpoint is the mobile api
if(endPoint.equalsIgnoreCase(Constants.MOBILE_SERVICE_BASE_URI)){
isMobileAPI = true;
}
//Create a rest adapter
return new Retrofit.Builder()
.client(createOkClient(isMobileAPI))
.baseUrl(endPoint)
.addConverterFactory(JacksonConverterFactory.create())
.build();
}
public static OkHttpClient createOkClient(boolean isMobileAPI){
NextModel next = NextModel.getInstance();
if(next.okClient == null || !isMobileAPI) {
//Create ok http Client
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
//Set timeouts
httpClient.readTimeout(Constants.TIMEOUT, TimeUnit.MILLISECONDS);
httpClient.connectTimeout(Constants.TIMEOUT, TimeUnit.MILLISECONDS);
CookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context));
//Add cookieJar to Http Client
httpClient.cookieJar(cookieJar);
//Create OkHttpClient
okHttpClient = httpClient.build();
return okHttpClient;
}else{
//Return already created okclient
return next.okClient;
}
}
public static OkHttpClient getOkClient() {
return okHttpClient;
}
}
我错过了什么?
提前致谢!
好的,我们发现了问题。我们缺少以下代码行:
RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),jsonObject.toString());
此代码在 POST 调用之前进入,而不是 POSTing jsonData,我们 post body 修复了它。希望 Android Studio 给出了某种错误来提示这一点。
完整方法:
private void getShortURL() {
//Get full url
final String fullURL = Constants.SHARE_BASE_URI + urlParams;
//Convert URL to JSON formatted data
Map<String,String> data = new HashMap<String,String>();
data.put("LINK",fullURL);
String jsonData = new GsonBuilder().create().toJson(data,Map.class);
RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonData);
//Call API and pass in JSON to get Short URL
Call<String> getDynamicLinkCall = RetrofitAdapter.getRetroInterface(Constants.BASE_URI).getDynamicLink_String(Constants.getTimestamp(),Constants.APPLICATION,"application/json", body);
getDynamicLinkCall.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (response == null || response.code() != Constants.SUCCESS) {
//Share Short URL
share(response.body().toString());
}
else
{
//If Short URl Failed share long URL
share(fullURL);
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
//If Short URl Failed share long URL
share(fullURL);
}
});
}
RetrofitINterface.java:
@POST("URLShortner")
Call<String> getDynamicLink_String(@Header("TimeStamp") String timestamp, @Header("Application") String application, @Header("Content-Type") String contentType, @Body RequestBody jsonData);
谢谢大家!