[英]Retrofit server response is getting 307 in android
第1步:需要向server.as提供输入,如下图所示
step2:
get response from server ,as below image.
![enter image description here][2]
step3:
MainActivity.java
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiInterface.URL_BASE)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
// prepare call in Retrofit 2.0
try {
JSONObject paramObject = new JSONObject();
paramObject.put("merchant_id", "aaaaa");
paramObject.put("secret_key", "bbbbb");
Call<RequestBody> userCall = apiInterface.getUser(paramObject.toString());
userCall.enqueue(this);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onResponse(Call<RequestBody> call, Response<RequestBody> response) {
Log.d("TEST","TEST--onResponse1---"+call);
Log.d("TEST","TEST--onResponse2---"+response);
}
@Override
public void onFailure(Call<RequestBody> call, Throwable t) {
Log.d("TEST","TEST--onFailure1--"+call);
Log.d("TEST","TEST--onFailure1--"+t);
}
========================================================
step4: ApiInterface.hava
public interface ApiInterface {
@Headers("Content-Type: application/json")
Call<RequestBody> getUser(@Body String body);
}
日志将“onResponse.code()”获得307“但我能够获得正确的数据。我是Retrofit服务的新手。可以帮助我。
如果不使用其他库,则无法将String
发送到Retrofit。
既然你已经在使用Gson了。 创建一个Gson可以序列化的类。
class Credentials {
@SerializedName("merchant_id")
public String merchantId;
@SerializedName("secret_key")
public String secretKey;
}
接口方法。 @Notice输入类型。
@Headers("Content-Type: application/json")
Call<RequestBody> getUser(@Body Credentials credentials);
307
是Temporary Redirect
- 您可能必须遵循该重定向。
这意味着,您需要配置OkHttpClient
来执行此操作:
OkHttpClient client = new OkHttpClient.Builder()
.followSslRedirects(true)
.followRedirects(true)
.build();
然后将其设置为retrofit2
的客户端:
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(Constants.API_BASE_URL)
.client(client)
.build();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.