我正在使用库com.squareup.retrofit:retrofit:1.9.0
,以便从我的安卓应用程序向我的服务器发送数据。
实际上,当我想向服务器发送一个请求时,我发现了这个错误:
failure : retrofit.RetrofitError: 307 Temporary Redirect
我尝试了许多想法,但同样的问题仍然存在。
请专家帮我解决这个问题。
问候
发布于 2017-02-22 14:44:18
您正在使用旧依赖项
将您的依赖项从“com.squareup.reverfit:retrofit:1.9.0”更改为
至
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
还要添加此依赖项以获取完整日志
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'.
将此方法添加到Retrofit客户端类中
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.connectTimeout("Your_Time", TimeUnit.SECONDS);
httpClient.readTimeout("Your_Time", TimeUnit.SECONDS);
httpClient.addInterceptor(logging);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("BASE URL")
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
下面的代码用于处理Http协议异常。
public Response post(String url, String content) throws IOException {
RequestBody body = RequestBody.create(PROTOCOL, content);
Request.Builder requestBuilder = new Request.Builder().url(url).post(body);
Request request = requestBuilder.build();
Response response = this.client.newCall(request).execute();
if(response.code() == 307) {
String location = response.header("Location");
return post(location, content);
}
return response;
}
发布于 2017-02-22 17:37:49
尝试放入HttpLoggingInterceptor
并检查日志。还要交叉检查Rest Client,看看您的服务器是否返回了正确的响应,以及是否提供了输入和参数。
对于HttpLoggingInterceptor
,这是以下配置方法
public RestClient() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(logging);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("BASEURL")
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
//APIInterface initiation
service = retrofit.create(APIInterface.class);
}
下面是相同的依赖项
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
如果您遵循启动rest客户端的其他一些可能性,请通过此Sample tutorial进行重新调整
发布于 2018-11-13 16:04:51
如果您想要处理所有307个响应,您可以创建并添加一个Interceptor
来完成此工作;此拦截器只需使用响应头"location“中指示的新路径创建一个新请求。
val client = OkHttpClient.Builder()
.addInterceptor {
val request = it.request()
val response = it.proceed(request)
if (response.code() == 307) {
val url = HttpUrl.Builder()
.scheme(request.url().scheme())
.host(request.url().host())
.addPathSegment(response.header("location", request.url().url().path)?: "")
.build()
val newRequest = Request.Builder()
.method(request.method(), request.body())
.url(url)
.headers(request.headers())
.build()
return@addInterceptor it.proceed(newRequest)
}
response
}
.build()
Retrofit.Builder().client(client).build()
https://stackoverflow.com/questions/34314695
复制相似问题