1.添加proxy_ios.h文件,内容如下:
#ifndef PROXY_IOS_H
#define PROXY_IOS_H
QString systemProxy();
#endif // PROXY_IOS_H
2.添加proxy_ios.mm文件,内容如下:
#import
#import
#include
QString systemProxy(){
NSDictionary *proxySettings = NSMakeCollectable([(NSDictionary *)CFNetworkCopySystemProxySettings() autorelease]);
NSArray *proxies = NSMakeCollectable([(NSArray *)CFNetworkCopyProxiesForURL((CFURLRef)[NSURL URLWithString:@"http://www.baidu.com"], (CFDictionaryRef)proxySettings) autorelease]);
NSDictionary *settings = [proxies objectAtIndex:0];
QString host = QString::fromNSString([NSString stringWithFormat:@"%@", [settings objectForKey:(NSString *)kCFProxyHostNameKey]]);
QString port = QString::fromNSString([NSString stringWithFormat:@"%@", [settings objectForKey:(NSString *)kCFProxyPortNumberKey]]);
// QString type = QString::fromNSString([NSString stringWithFormat:@"%@", [settings objectForKey:(NSString *)kCFProxyTypeKey]]);
return host+":"+port;
}
3.在.pro工程文件中添加:
ios {
QMAKE_LFLAGS += -framework OpenGLES
QMAKE_LFLAGS += -framework GLKit
QMAKE_LFLAGS += -framework QuartzCore
QMAKE_LFLAGS += -framework CoreVideo
QMAKE_LFLAGS += -framework CoreAudio
QMAKE_LFLAGS += -framework CoreImage
QMAKE_LFLAGS += -framework CoreMedia
QMAKE_LFLAGS += -framework AVFoundation
QMAKE_LFLAGS += -framework AudioToolbox
QMAKE_LFLAGS += -framework CoreGraphics
QMAKE_LFLAGS += -framework UIKit
QMAKE_LFLAGS += -framework CFNetwork
}
4.使用Qt添加proxy_ios.h和proxy_ios.mm文件。
5.在main.cpp文件中调用如下:
#include "proxy_ios.h"
void setDefaultProxy(){
QString hostport = systemProxy();
qDebug() <<"had find proxy address:" << hostport;
if(!hostport.isEmpty()){
QStringList ip_port = hostport.split(':');
if(ip_port.length() != 2){
return;
}
QString host = ip_port.at(0);
QString port = ip_port.at(1);
if(host.contains("null") || port.contains("null")){
return;
}
bool ok = false;
int iport = port.toInt(&ok);
if(!ok || iport <= 0){
return;
}
QNetworkProxy proxy;
proxy.setType(QNetworkProxy::HttpProxy);//设置类型
proxy.setHostName(host);//设置代理服务器地址
proxy.setPort(iport);//设置端口
QNetworkProxy::setApplicationProxy(proxy);
qDebug() <<"+++had set proxy address:" << hostport;
}
}
6.编译即可。