哪位电信大神卡套餐内容知道广东移动有什么好套餐的

4022人阅读
在网络操作中,经常会由于各种原因引起网络连接超时,究竟何为网络连接超时?
网络连接超时:在程序默认的等待时间内没有得到服务器的响应
引起网络连接超时的原因很多,下面,列举一些常见的原因:
网络断开,不过经常显示无法连接
网络阻塞,导致你不能在程序默认等待时间内得到回复数据包
网络不稳定,网络无法完整传送服务器信息
系统问题,系统资源过低,无法为程序提供足够的资源处理服务器信息
设备不稳定,如网线松动、接口没插好等等
网络注册时系统繁忙,无法回应
网速过慢,如 使用 BT 多线程下载,在线收看视频等大量占用带宽的软件 ,若使用共享带宽还要防范他人恶意占用带宽
计算机感染了恶意软件,计算机病毒,计算机木马等
Qt 中的网络连接超时
在 Qt 中,关于 QNetworkAccessManager、QNetworkRequest 和 QNetworkReply 的文档中,找到了有关超时相关的错误 QNetworkReply::NetworkError。
常量 QNetworkReply::TimeoutError:
the connection to the remote server timed out
瞬间欣喜若狂,既然有超时错误,必然有设置超时的接口吧!遗憾,遗憾,遗憾。。。重要的事情说 3 遍,翻遍了官方文档,能和超时扯上关系的就这么一个简单的常量说明(当然还有 QNetworkReply::ProxyTimeoutError)。
这种情况下,我们只能自己去处理超时了。
如何处理超时
解决思路:
使用 QTimer 启动一个单次定时器,并设置超时时间。
在事件循环退出之后,判断定时器的状态,如果是激活状态,证明请求已经完成;否则,说明超时。
来看一个简单的例子 - 获取
网页内容:
timer.setInterval(30000);
timer.setSingleShot(true);
QNetworkAccessM
request.setUrl(QUrl("http://qt-project.org"));
request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");
QNetworkReply *pReply = manager.get(request);
QEventLoop loop;
connect(&timer, &QTimer, &loop, &QEventLoop);
connect(pReply, &QNetworkReply, &loop, &QEventLoop);
timer.start();
loop.exec();
if (timer.isActive()) {
timer.stop();
if (pReply-&error() != QNetworkReply) {
qDebug() && "Error String : " && pReply-&errorString();
QVariant variant = pReply-&attribute(QNetworkRequest);
int nStatusCode = variant.toInt();
qDebug() && "Status Code : " && nStatusC
disconnect(pReply, &QNetworkReply, &loop, &QEventLoop);
pReply-&abort();
pReply-&deleteLater();
qDebug() && "Timeout";
首先,定义一个 QTimer,设置超时时间为 30000 毫秒(30 秒)并设置为单次触发。然后,使用 QNetworkRequest 实现一个简单的网络请求,通过 QNetworkAccessManager::get() 开始获取 Qt 官网的 HTML 页面内容。因为请求过程是异步的,所以通过使用 QEventLoop 启动一个事件循环让其同步处理,并将 QTimer 的 timeout() 信号以及 QNetworkReply 的 finished() 信号连接至其 quit() 槽函数,保证在定时器过期之后或者网络响应完成后事件循环得到退出,不至于一直处于阻塞状态。
如上所述,事件循环退出的两种情况:
QTimer 30 秒到期,超时
网络连接响应完成
所以,当 QTimer::isActive() 激活的情况下,证明响应完成,还尚未超时。这时需要先调用 QTimer::stop() 来停止定时器,再对响做进一步处理。否则,进行超时处理 - QNetworkReply::abort() 立即中止操作并关闭网络连接。
既然以后会经常用到,那么还是提供一个封装类 QReplyTimeout 专门处理超时。
#include &QObject&
#include &QTimer&
#include &QNetworkReply&
class QReplyTimeout : public QObject {
QReplyTimeout(QNetworkReply *reply, const int timeout) : QObject(reply) {
Q_ASSERT(reply);
if (reply && reply-&isRunning()) {
QTimer::singleShot(timeout, this, SLOT(onTimeout()));
void timeout();
private slots:
void onTimeout() {
QNetworkReply *reply = static_cast&QNetworkReply*&(parent());
if (reply-&isRunning()) {
reply-&abort();
reply-&deleteLater();
emit timeout();
由于 QNetworkReply 和 QReplyTimeout 是父子关系,所以 QReplyTimeout 将被自动销毁。
使用起来非常简单:
QNetworkAccessManager *pManger = new QNetworkAccessManager(this);
QNetworkReply *pReply = pManger-&get(QNetworkRequest(QUrl("")));
QReplyTimeout *pTimeout = new QReplyTimeout(pReply, 1000);
connect(pTimeout, &QReplyTimeout::timeout, [=]() {
qDebug() && "Timeout";
如果对 Google 的获取未在 1000 毫秒(1 秒)内完成,则会中止,并发出 timeout() 信号,供进一步处理(例如:提示用户请求超时)。
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
Qter,还在等什么,赶快加入吧!
Qt分享&&交流
QML分享&&交流
访问:1418090次
积分:18891
积分:18891
排名:第423名
原创:366篇
评论:1452条
本博客中所有原创文章及译文均采用进行许可
文章:13篇
阅读:9127
文章:14篇
阅读:16916
文章:39篇
阅读:60126
文章:36篇
阅读:39408
阅读:30062
阅读:11738
文章:215篇
阅读:1006904
(5)(11)(11)(21)(2)(11)(10)(18)(29)(37)(24)(59)(28)(19)(9)(28)(5)(15)(12)(17)【开源项目13】Volley框架 以及 设置request超时时间 - 推酷
【开源项目13】Volley框架 以及 设置request超时时间
Volley提供了优美的框架,使android程序网络访问更容易、更快。
Volley抽象实现了底层的HTTP Client库,我们不需关注HTTP Client细节,专注于写出更加漂亮、干净的RESTful HTTP请求。
Volley请求会异步执行,不阻挡主线程。
Volley提供的功能
封装了异步的RESTful请求API
一个优雅and稳健的请求队列
一个可扩展的架构,使开发者能实现自定义的请求和响应处理机制
能使用外部Http Client库
自定义的网络图像加载视图(NetworkImageView,ImageLoader等)
为什么使用异步Http请求
Android中要求HTTP请求异步执行,如果在主线程执行HTTP请求,可能会抛出 android.os.NetworkOnMainThreadException&&异常。阻塞主线程有一些严重的后果,它阻碍UI渲染,用户体验不流 畅,它可能会导致可怕的ANR(Application Not Responding)。要避免这些陷阱,作为一个开发者,应该始终确保HTTP请求是在一个不同的线程
怎样使用Volley
1、安装和使用Volley库
2、使用请求队列
3、异步的JSON、String请求
4、取消请求
5、重试失败的请求,自定义请求超时
6、设置请求头(HTTP headers)
7、使用Cookies
8、错误处理
1.安装和使用Volley库
引入Volley非常简单,首先,从git库先克隆一个下来:
git clone /platform/frameworks/volley
然后编译为jar包,再把jar包放到自己的工程的libs目录。
2.使用请求队列
Volley的所有请求都放在一个队列,然后进行处理,这里是你如何将创建一个请求队列:
RequestQueue mRequestQueue = Volley.newRequestQueue(this); // 'this' is Context
理想的情况是把请求队列集中放到一个地方,最好是初始化应用程序类中初始化请求队列,下面类做到了这一点:
public class ApplicationController extends Application {
* Log or request TAG
public static final String TAG = &VolleyPatterns&;
* Global request queue for Volley
private RequestQueue mRequestQ
* A singleton instance of the application class for easy access in other places
private static ApplicationController sI
public void onCreate() {
super.onCreate();
// initialize the singleton
sInstance = this;
* @return ApplicationController singleton instance
public static synchronized ApplicationController getInstance() {
* @return The Volley Request queue, the queue will be created if it is null
public RequestQueue getRequestQueue() {
// lazy initialize the request queue, the queue instance will be
// created when it is accessed for the first time
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
return mRequestQ
* Adds the specified request to the global queue, if tag is specified
* then it is used else Default TAG is used.
* @param req
* @param tag
public &T& void addToRequestQueue(Request&T& req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
VolleyLog.d(&Adding request to queue: %s&, req.getUrl());
getRequestQueue().add(req);
* Adds the specified request to the global queue using the Default TAG.
* @param req
* @param tag
public &T& void addToRequestQueue(Request&T& req) {
// set the default tag if tag is empty
req.setTag(TAG);
getRequestQueue().add(req);
* Cancels all pending requests by the specified TAG, it is important
* to specify a TAG so that the pending/ongoing requests can be cancelled.
* @param tag
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
3.异步的JSON、String请求
Volley提供了以下的实用工具类进行异步HTTP请求:
JsonObjectRequest&— To send and receive JSON Object from the Server
JsonArrayRequest&— To receive JSON Array from the Server
StringRequest&— To retrieve response body as String (ideally if you intend to parse the response by yourself)
JsonObjectRequest
这个类可以用来发送和接收JSON对象。这个类的一个重载构造函数允许设置适当的请求方法(DELETE,GET,POST和PUT)。如果您正在使用一个RESTful服务端,可以使用这个类。下面的示例显示如何使GET和POST请求
final String URL = &/volley/resource/12&;
// pass second argument as &null& for GET requests
JsonObjectRequest req = new JsonObjectRequest(URL, null,
new Response.Listener&JSONObject&() {
public void onResponse(JSONObject response) {
VolleyLog.v(&Response:%n %s&, response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
VolleyLog.e(&Error: &, error.getMessage());
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
POST请求:
final String URL = &/volley/resource/12&;
// Post params to be sent to the server
HashMap&String, String& params = new HashMap&String, String&();
params.put(&token&, &AbCdEfGh123456&);
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener&JSONObject&() {
public void onResponse(JSONObject response) {
VolleyLog.v(&Response:%n %s&, response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
VolleyLog.e(&Error: &, error.getMessage());
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
JsonArrayRequest
这个类可以用来接受 JSON Arrary,不支持JSON Object。这个类现在只支持 HTTP GET。由于支持GET,你可以在URL的后面加上请求参数。类的构造函数不支持请求参数
final String URL = &/volley/resource/all?count=20&;
JsonArrayRequest req = new JsonArrayRequest(URL, new Response.Listener&JSONArray& () {
public void onResponse(JSONArray response) {
VolleyLog.v(&Response:%n %s&, response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
VolleyLog.e(&Error: &, error.getMessage());
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
StringRequest
这个类可以用来从服务器获取String,如果想自己解析请求响应可以使用这个类,例如返回xml数据。它还可以使用重载的构造函数定制请求
final String URL = &/volley/resource/recent.xml&;
StringRequest req = new StringRequest(URL, new Response.Listener&String&() {
public void onResponse(String response) {
VolleyLog.v(&Response:%n %s&, response);
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
VolleyLog.e(&Error: &, error.getMessage());
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
4.取消请求
Volley提供了强大的API取消未处理或正在处理的请求。取消请求最简单的方法是调用请求队列cancelAll(tag)的方法,前提是你在添加请求时设置了标记。这样就能使标签标记的请求挂起。
给请求设置标签:
request.setTag(&My Tag&);
使用ApplicationController添加使用了标签的请求到队列中:
ApplicationController.getInstance().addToRequestQueue(request, &My Tag&);
取消所有指定标记的请求:
mRequestQueue.cancelAll(&My Tag&);
5.重试失败的请求,自定义请求超时
Volley中没有指定的方法来设置请求超时时间,可以设置RetryPolicy 来变通实现。DefaultRetryPolicy类有个initialTimeout参数,可以设置超时时间。要确保最大重试次数为1,以保证超时后不重新请求。
Setting Request Timeout
request.setRetryPolicy(new DefaultRetryPolicy(20 * .0f));
设置请求头(HTTP headers)& & & & 如果你想失败后重新请求(因超时),您可以指定使用上面的代码,增加重试次数。注意最后一个参数,它允许你指定一个退避乘数可以用来实现“指数退避”来从RESTful服务器请求数据。
有时候需要给HTTP请求添加额外的头信息,一个常用的例子是添加 “Authorization”到HTTP 请求的头信息。Volley请求类提供了一个 getHeaers()的方法,重载这个方法可以自定义HTTP 的头信息。
添加头信息:
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener&JSONObject&() {
public void onResponse(JSONObject response) {
// handle response
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
// handle error
public Map&String, String& getHeaders() throws AuthFailureError {
HashMap&String, String& headers = new HashMap&String, String&();
headers.put(&CUSTOM_HEADER&, &Yahoo&);
headers.put(&ANOTHER_CUSTOM_HEADER&, &Google&);
6.使用Cookies
Volley中没有直接的API来设置cookies,Volley的设计理念就是提供干净、简洁的API来实现RESTful HTTP请求,不提供设置cookies是合理的。
下面是修改后的ApplicationController类,这个类修改了getRequestQueue()方法,包含了 设置cookie方法,这些修改还是有些粗糙
// http client instance
private DefaultHttpClient mHttpC
public RequestQueue getRequestQueue() {
// lazy initialize the request queue, the queue instance will be
// created when it is accessed for the first time
if (mRequestQueue == null) {
// Create an instance of the Http client.
// We need this in order to access the cookie store
mHttpClient = new DefaultHttpClient();
// create the request queue
mRequestQueue = Volley.newRequestQueue(this, new HttpClientStack(mHttpClient));
return mRequestQ
* Method to set a cookie
public void setCookie() {
CookieStore cs = mHttpClient.getCookieStore();
// create a cookie
cs.addCookie(new BasicClientCookie2(&cookie&, &spooky&));
// add the cookie before adding the request to the queue
setCookie();
// add the request to the queue
mRequestQueue.add(request);
7.错误处理
正如前面代码看到的,在创建一个请求时,需要添加一个错误监听onErrorResponse。如果请求发生异常,会返回一个VolleyError实例。
以下是Volley的异常列表:
AuthFailureError:如果在做一个HTTP的身份验证,可能会发生这个错误。
NetworkError:Socket关闭,服务器宕机,DNS错误都会产生这个错误。
NoConnectionError:和NetworkError类似,这个是客户端没有网络连接。
ParseError:在使用JsonObjectRequest或JsonArrayRequest时,如果接收到的JSON是畸形,会产生异常。
SERVERERROR:服务器的响应的一个错误,最有可能的4xx或5xx HTTP状态代码。
TimeoutError:Socket超时,服务器太忙或网络延迟会产生这个异常。默认情况下,Volley的超时时间为2.5秒。如果得到这个错误可以使用RetryPolicy。
可以使用一个简单的Help类根据这些异常提示相应的信息:
public class VolleyErrorHelper {
* Returns appropriate message which is to be displayed to the user
* against the specified error object.
* @param error
* @param context
public static String getMessage(Object error, Context context) {
if (error instanceof TimeoutError) {
return context.getResources().getString(R.string.generic_server_down);
else if (isServerProblem(error)) {
return handleServerError(error, context);
else if (isNetworkProblem(error)) {
return context.getResources().getString(R.string.no_internet);
return context.getResources().getString(R.string.generic_error);
* Determines whether the error is related to network
* @param error
private static boolean isNetworkProblem(Object error) {
return (error instanceof NetworkError) || (error instanceof NoConnectionError);
* Determines whether the error is related to server
* @param error
private static boolean isServerProblem(Object error) {
return (error instanceof ServerError) || (error instanceof AuthFailureError);
* Handles the server error, tries to determine whether to show a stock message or to
* show a message retrieved from the server.
* @param err
* @param context
private static String handleServerError(Object err, Context context) {
VolleyError error = (VolleyError)
NetworkResponse response = error.networkR
if (response != null) {
switch (response.statusCode) {
// server might return error like this { &error&: &Some error occured& }
// Use &Gson& to parse the result
HashMap&String, String& result = new Gson().fromJson(new String(response.data),
new TypeToken&Map&String, String&&() {
}.getType());
if (result != null && result.containsKey(&error&)) {
return result.get(&error&);
} catch (Exception e) {
e.printStackTrace();
// invalid request
return error.getMessage();
return context.getResources().getString(R.string.generic_server_down);
return context.getResources().getString(R.string.generic_error);
Volley是一个非常好的库,你可以尝试使用一下,它会帮助你简化网络请求,带来更多的益处。
我也希望更加全面的介绍Volley,以后可能会介绍使用volley加载图像的内容,欢迎关注
已发表评论数()
请填写推刊名
描述不能大于100个字符!
权限设置: 公开
仅自己可见
正文不准确
标题不准确
排版有问题
主题不准确
没有分页内容
图片无法显示
视频无法显示
与原文不一致

我要回帖

更多关于 电信大神卡套餐内容 的文章

 

随机推荐