自己动手实现OkHttp

}

if (userRequest.header(“User-Agent”) == null) {
requestBuilder.header(“User-Agent”, Version.userAgent());
}

}

2. 支持自动重定向

有时我们请求的URL已经被移走了,此时server会返回301状态码和一个重定向的新URL,此时我们要能够支持自动访问新URL而不是向用户报错。

对于重定向这里有一个测试性URL:www.publicobject.com/helloworld.… ,通过访问并抓包,可以看到如下信息:

因此,我们在接收到Response后要根据status_code是否为重定向,如果是,则要从Response Header里解析出新的URL-Location并自动请求新URL。那么,我们可以继续改写sendRequest(request)方法:

[class WingjayHttpClient]

private boolean allowRedirect = true;
// user can set redirect status when building WingjayHttpClient
public void setAllowRedirect(boolean allowRedirect) {
this.allowRedirect = allowRedirect;
}

public Response sendRequest(Request userRequest) {
Request httpRequest = expandHeaders(userRequest);
Response response = executeRequest(httpRequest);
switch (response.statusCode()) {
// 300: multi choice; 301: moven permanently;
// 302: moved temporarily; 303: see other;
// 307: redirect temporarily; 308: redirect permanently
case 300:
case 301:
case 302:
case 303:
case 307:
case 308:
return handleRedirect(response);
default:
return response;
}

}
// the max times of followup request
private static final int MAX_FOLLOW_UPS = 20;
private int followupCount = 0;

private Response handleRedirect(Response response) {
// Does the WingjayHttpClient allow redirect?
if (!client.allowRedirect()) {
return null;
}

// Get the redirecting url
String nextUrl = response.header(“Location”);

// Construct a redirecting request
Request followup = new Request(nextUrl);

// check the max followupCount
if (++followupCount > MAX_FOLLOW_UPS) {
throw new Exception("Too many follow-up requests: " + followUpCount);
}

// not reach the max followup times, send followup request then.
return sendRequest(followup);
}

利用上面的代码,我们通过获取原始userRequest的返回结果,判断结果是否为重定向,并做出自动followup处理。

一些常用的状态码 100~199:指示信息,表示请求已接收,继续处理 200~299:请求成功,表示请求已被成功接收、理解、接受 300~399:重定向,要完成请求必须进行更进一步的操作 400~499:客户端错误,请求有语法错误或请求无法实现 500~599:服务器端错误,服务器未能实现合法的请求

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值