Java源码示例:com.arronlong.httpclientutil.common.HttpConfig
示例1
/**
* 推送信息
* @param url
* @param data
*/
public static String push(String url, String data, NotificationConfig buildConfig) throws HttpProcessException {
HttpConfig httpConfig;
//使用代理请求
if(buildConfig.useProxy){
HttpClient httpClient;
HttpHost proxy = new HttpHost(buildConfig.proxyHost, buildConfig.proxyPort);
//用户密码
if(StringUtils.isNotEmpty(buildConfig.proxyUsername) && buildConfig.proxyPassword != null){
// 设置认证
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(buildConfig.proxyUsername, Secret.toString(buildConfig.proxyPassword)));
httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).setProxy(proxy).build();
}else{
httpClient = HttpClients.custom().setProxy(proxy).build();
}
//代理请求
httpConfig = HttpConfig.custom().client(httpClient).url(url).json(data).encoding("utf-8");
}else{
//普通请求
httpConfig = HttpConfig.custom().url(url).json(data).encoding("utf-8");
}
String result = HttpClientUtil.post(httpConfig);
return result;
}
示例2
/**
* Gets city by ip addr.
*
* @param ipAddr the ip addr
*
* @return the city by ip addr
*/
public static GaodeLocation getCityByIpAddr(String ipAddr) {
// http://lbs.amap.com/api/webservice/guide/api/ipconfig/
log.info("getCityByIpAddr - 根据IP定位. ipAddr={}", ipAddr);
GaodeLocation location = null;
String urlAddressIp = "http://restapi.amap.com/v3/ip?key=f8bdce6f882a98635bb0b7b897331327&ip=%s";
String url = String.format(urlAddressIp, ipAddr);
try {
String str = HttpClientUtil.get(HttpConfig.custom().url(url));
location = new ObjectMapper().readValue(str, GaodeLocation.class);
} catch (Exception e) {
log.error("getCityByIpAddr={}", e.getMessage(), e);
}
log.info("getCityByIpAddr - 根据IP定位. ipAddr={}, location={}", ipAddr, location);
return location;
}
示例3
/**
* 测试启用http连接池,get100次,down20次的执行时间
* @throws HttpProcessException
*/
private static void testByPool(int getCount, int downCount) throws HttpProcessException {
long start = System.currentTimeMillis();
HCB hcb= HCB.custom().pool(100, 10).ssl();
if(getCount>0){
HttpConfig cfg3 = HttpConfig.custom().client(hcb.build()).headers(headers);//使用一个client对象
testMultiGet(cfg3, getCount);
}
if(downCount>0){
HttpConfig cfg4 = HttpConfig.custom().client(hcb.build()).timeout(10000);
File file = new File(filePath);
if(!file.exists()){
file.mkdirs();
}
testMultiDown(cfg4, downCount);
}
System.out.println("-----所有线程已完成!------");
long end = System.currentTimeMillis();
System.out.println("总耗时(毫秒): -> " + (end - start));
buf.append("\t").append((end-start));
}
示例4
/**
* 快速测试pool的应用(通过运行httpConn.bat监控http连接数,查看是否启用连接池)
*
* @throws HttpProcessException
*/
public static void testquickConcurrent() throws HttpProcessException{
//---------------------------
//--- 期望结果:
// 由于urls中有3个域名,所以会为每个域名最多建立20个http链接,
// 通过上面的监控,应该会看到http连接数会增加3-20=60个左右
//---------------------------
HttpClient client= HCB.custom().pool(100, 20).timeout(10000).build();//最多创建20个http链接
final HttpConfig cfg = HttpConfig.custom().client(client).headers(headers);//为每次请求创建一个实例化对象
for (int i = 0; i < 100; i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
int idx = ((int) (Math.random() * 10)) % 5;
HttpClientUtil.get(cfg.url(urls[idx]));
System.out.println("---idx="+idx);
} catch (HttpProcessException e) {
}
}
}).start();
}
}
示例5
public static void main(String[] args) throws HttpProcessException {
//登录后,为上传做准备
HttpConfig config = prepareUpload();
String url= "http://test.free.800m.net:8080/up.php?action=upsave";//上传地址
// String[] filePaths = {"D:\\中国.txt","D:\\111.txt","C:\\Users\\160049\\Desktop\\中国.png"};//待上传的文件路径
String[] filePaths = {"D:\\中国支付清算系统总体架构图-无文字版.png"};//待上传的文件路径
Map<String, Object> map = new HashMap<String, Object>();
map.put("path", "./tomcat/vhost/test/ROOT/");//指定其他参数
config.url(url) //设定上传地址
.encoding("GB2312") //设定编码,否则可能会引起中文乱码或导致上传失败
.files(filePaths,"myfile",true)//.files(filePaths),如果服务器端有验证input 的name值,则请传递第二个参数,如果上传失败,则尝试第三个参数设置为true
.map(map);//其他需要提交的参数
Utils.debug();//开启打印日志,调用 Utils.debug(false);关闭打印日志
String r = HttpClientUtil.upload(config);//上传
System.out.println(r);
}
示例6
/**
* 登录,并上传文件
*
* @return
* @throws HttpProcessException
*/
private static HttpConfig prepareUpload() throws HttpProcessException {
String url ="http://test.free.800m.net:8080/";
String loginUrl = url+"login.php";
String indexUrl = url+"index.php";
HttpCookies cookies = HttpCookies.custom();
//启用cookie,用于登录后的操作
HttpConfig config = HttpConfig.custom().context(cookies.getContext());
Map<String, Object> map = new HashMap<String, Object>();
map.put("user_name", "test");
map.put("user_pass", "800m.net");
map.put("action", "login");
String loginResult = HttpClientUtil.post(config.url(loginUrl).map(map));
System.out.println("是否登录成功:"+loginResult.contains("成功"));
//打开主页
HttpClientUtil.get(config.map(null).url(indexUrl));
return config;
}
示例7
/**
* 直接获取网络验证码(验证码不刷新)
*
* @param imgUrl 验证码地址
* @param limitCodeLen 验证码长度
* @return 返回识别的验证码结果
*/
public static String ocrCode4Net(String imgUrl, int limitCodeLen){
Map<String, Object> map = getParaMap();
map.put("url", imgUrl);
Header[] headers = HttpHeader.custom().userAgent("Mozilla/5.0 (Windows NT 5.1; zh-CN; rv:1.9.1.3) Gecko/20100101 Firefox/8.0").build();
try {
String html = HttpClientUtil.post(HttpConfig.custom().client(client).url(apiUrl).headers(headers).map(map));
//System.out.println(html);
String[] results = StringUtil.regex("<Result>([^<]*)</Result>\\s*<Status>([^<]*)</Status>", html);
if(results.length>0){
//System.out.println(results[0]);
if(Boolean.parseBoolean(results[1])){
if(limitCodeLen<=0 || limitCodeLen==results[0].length()){//不判断长度或者长度一致时,直接返回
return results[0];
}else{
return "Error:获取失败! 原因:识别结果长度为:"+results[0].length()+"(期望长度:"+limitCodeLen+")";
}
}else{
return "Error:获取失败! 原因:"+results[0];
}
}
} catch (HttpProcessException e) {
Utils.exception(e);
}
return "Error:获取失败!";
}
示例8
public static void main(String[] args) throws HttpProcessException, IOException {
// enableCatch();
String filePath="C:/Users/160049/Desktop/中国.png";
String url = "http://file.ocrking.net:6080/small/20161104/w4fCjnzCl8KTwphpwqnCv2bCn8Kp/66fcff8d-61b1-49d6-bbfe-7428cf7accdf_debug.png?e9gFvJmkLbmgsZNTUCCNkjfi8J0Wbpn1CZHeP98eT1kxZ0ISBDt8Ql6h6zQ79pJg";
String url2 = "http://59.41.9.91/GZCX/WebUI/Content/Handler/ValidateCode.ashx?0.3271647585525703";
String code1 = ocrCode(filePath, 5);
String code2 = ocrCode4Net(url,5);
String code3 = ocrCode4Net(HttpConfig.custom().url(url2), System.getProperty("user.dir")+System.getProperty("file.separator")+"123.png", 5);
System.out.println(code1);
System.out.println(code2);
System.out.println(code3);
System.out.println("----");
}
示例9
/**
* 识别本地校验码(英文:字母+大小写)
*
* @param imgFilePath 验证码地址
* @param limitCodeLen 验证码长度(如果结果与设定长度不一致,则返回获取失败的提示)
* @return 返回识别的验证码结果
*/
public static String ocrCode(String imgFilePath, int limitCodeLen){
//读取文件
File f = new File(imgFilePath);
if(!f.exists()){
return "Error:文件不存在!";
}
String html;
try {
html = HttpClientUtil.upload(HttpConfig.custom().client(client).url(apiUrl).files(new String[]{imgFilePath},"ocrfile",true).map(getParaMap()));
//System.out.println(html);
String[] results = StringUtil.regex("<Result>([^<]*)</Result>\\s*<Status>([^<]*)</Status>", html);
if(results.length>0){
//System.out.println(results[0]);
if(Boolean.parseBoolean(results[1])){
if(limitCodeLen<=0 || limitCodeLen==results[0].length()){//不判断长度或者长度一致时,直接返回
return results[0];
}else{
return "Error:获取失败! 原因:识别结果长度为:"+results[0].length()+"(期望长度:"+limitCodeLen+")";
}
}else{
return "Error:获取失败! 原因:"+results[0];
}
}
} catch (HttpProcessException e) {
Utils.exception(e);
}
return "Error:获取失败!";
}
示例10
/**
* 直接获取网络验证码(验证码不刷新)
*
* @param imgUrl 验证码地址
* @param limitCodeLen 验证码长度
* @return 返回识别的验证码结果
*/
public static String ocrCode4Net(String imgUrl, int limitCodeLen){
Map<String, Object> map = getParaMap();
map.put("url", imgUrl);
Header[] headers = HttpHeader.custom().userAgent("Mozilla/5.0 (Windows NT 5.1; zh-CN; rv:1.9.1.3) Gecko/20100101 Firefox/8.0").build();
try {
String html = HttpClientUtil.post(HttpConfig.custom().client(client).url(apiUrl).headers(headers).map(map));
//System.out.println(html);
String[] results = StringUtil.regex("<Result>([^<]*)</Result>\\s*<Status>([^<]*)</Status>", html);
if(results.length>0){
//System.out.println(results[0]);
if(Boolean.parseBoolean(results[1])){
if(limitCodeLen<=0 || limitCodeLen==results[0].length()){//不判断长度或者长度一致时,直接返回
return results[0];
}else{
return "Error:获取失败! 原因:识别结果长度为:"+results[0].length()+"(期望长度:"+limitCodeLen+")";
}
}else{
return "Error:获取失败! 原因:"+results[0];
}
}
} catch (HttpProcessException e) {
Utils.exception(e);
}
return "Error:获取失败!";
}
示例11
public static void main(String[] args) throws HttpProcessException, IOException {
String filePath="C:/Users/160049/Desktop/中国.png";
String url = "http://file.ocrking.net:6080/small/20161104/w4fCjnzCl8KTwphpwqnCv2bCn8Kp/66fcff8d-61b1-49d6-bbfe-7428cf7accdf_debug.png?e9gFvJmkLbmgsZNTUCCNkjfi8J0Wbpn1CZHeP98eT1kxZ0ISBDt8Ql6h6zQ79pJg";
String url2 = "http://59.41.9.91/GZCX/WebUI/Content/Handler/ValidateCode.ashx?0.3271647585525703";
String code1 = ocrCode(filePath, 5);
String code2 = ocrCode4Net(url,5);
String code3 = ocrCode4Net(HttpConfig.custom().url(url2), System.getProperty("user.dir")+System.getProperty("file.separator")+"123.png", 5);
System.out.println(code1);
System.out.println(code2);
System.out.println(code3);
System.out.println("----");
}
示例12
/**
* 判定是否开启连接池、及url是http还是https <br>
* 如果已开启连接池,则自动调用build方法,从连接池中获取client对象<br>
* 否则,直接返回相应的默认client对象<br>
*
* @param config 请求参数配置
* @throws HttpProcessException http处理异常
*/
private static void create(HttpConfig config) throws HttpProcessException {
if(config.client()==null){//如果为空,设为默认client对象
if(config.url().toLowerCase().startsWith("https://")){
config.client(client4HTTPS);
}else{
config.client(client4HTTP);
}
}
}
示例13
/**
* 请求资源或服务,返回HttpResult对象
*
* @param config 请求参数配置
* @return 返回HttpResult处理结果
* @throws HttpProcessException http处理异常
*/
public static HttpResult sendAndGetResp(HttpConfig config) throws HttpProcessException {
Header[] reqHeaders = config.headers();
//执行结果
HttpResponse resp = execute(config);
HttpResult result = new HttpResult(resp);
result.setResult(fmt2String(resp, config.outenc()));
result.setReqHeaders(reqHeaders);
return result;
}
示例14
public static void testMultiGet(HttpConfig cfg, int count) throws HttpProcessException{
try {
int pagecount = urls.length;
ExecutorService executors = Executors.newFixedThreadPool(pagecount);
CountDownLatch countDownLatch = new CountDownLatch(count);
//启动线程抓取
for(int i = 0; i< count;i++){
executors.execute(new GetRunnable(countDownLatch,cfg, urls[i%pagecount]));
}
countDownLatch.await();
executors.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
示例15
public static void main(String[] args) throws InterruptedException, HttpProcessException {
String qq = "123456789";//qq号
String imgUrl = "http://qqxoo.com/include/vdimgvt.php?t="+Math.random(); //获取验证码图片地址
String verifyUrl = "http://qqxoo.com/include/vdcheck.php";
String saveCodePath = "C:/1.png";//保存验证码图片路径
Header[] headers = HttpHeader.custom().referer("http://qqxoo.com/main.html?qqid="+qq).build();//设置referer,是为了获取对应qq号的验证码,否则报错
HttpConfig config = HttpConfig.custom().headers(headers).context(HttpCookies.custom().getContext());//必须设置context,是为了携带cookie进行操作
String result =null;//识别结果
do {
if(result!=null){
System.err.println("校验失败!稍等片刻后继续识别");
Thread.sleep((int)(Math.random()*10)*100);
}
//获取验证码
//OCR.debug(); //开始Fiddler4抓包(127.0.0.1:8888)
String code = OCR.ocrCode4Net(config.url(imgUrl), saveCodePath);
while(code.length()!=5){//如果识别的验证码位数不等于5,则重新识别
if(code.contains("亲,apiKey已经过期或错误,请重新获取")){
System.err.println(code);
return;
}
code = OCR.ocrCode4Net(config.url(imgUrl), saveCodePath);
}
System.out.println("本地识别的验证码为:"+code);
System.out.println("验证码已保存到:"+saveCodePath);
System.out.println("开始校验验证码是否正确");
//开始验证识别的验证码是否正确
result = HttpClientUtil.get(config.url(verifyUrl+"?vc="+code+"&qqid="+qq));
} while (!result.contains("succeed"));
System.out.println("识别验证码成功!反馈信息如下:\n" + result);
}
示例16
/**
* 请求资源或服务
*
* @param config 请求参数配置
* @return 返回HttpResponse对象
* @throws HttpProcessException http处理异常
*/
private static HttpResponse execute(HttpConfig config) throws HttpProcessException {
create(config);//获取链接
HttpResponse resp = null;
try {
//创建请求对象
HttpRequestBase request = getRequest(config.url(), config.method());
//设置超时
request.setConfig(config.requestConfig());
//设置header信息
request.setHeaders(config.headers());
//判断是否支持设置entity(仅HttpPost、HttpPut、HttpPatch支持)
if(HttpEntityEnclosingRequestBase.class.isAssignableFrom(request.getClass())){
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if(request.getClass()==HttpGet.class) {
//检测url中是否存在参数
//注:只有get请求,才自动截取url中的参数,post等其他方式,不再截取
config.url(Utils.checkHasParas(config.url(), nvps, config.inenc()));
}
//装填参数
HttpEntity entity = Utils.map2HttpEntity(nvps, config.map(), config.inenc());
//设置参数到请求对象中
((HttpEntityEnclosingRequestBase)request).setEntity(entity);
Utils.info("请求地址:"+config.url());
if(nvps.size()>0){
Utils.info("请求参数:"+nvps.toString());
}
if(config.json()!=null){
Utils.info("请求参数:"+config.json());
}
}else{
int idx = config.url().indexOf("?");
Utils.info("请求地址:"+config.url().substring(0, (idx>0 ? idx : config.url().length())));
if(idx>0){
Utils.info("请求参数:"+config.url().substring(idx+1));
}
}
//执行请求操作,并拿到结果(同步阻塞)
resp = (config.context()==null)?config.client().execute(request) : config.client().execute(request, config.context()) ;
if(config.isReturnRespHeaders()){
//获取所有response的header信息
config.headers(resp.getAllHeaders());
}
//获取结果实体
return resp;
} catch (IOException e) {
throw new HttpProcessException(e);
}
}
示例17
public static void main(String[] args) throws HttpProcessException {
final String url = "http://jd.com/?"+Math.random();
// final String url2 = "https://www.facebook.com/?"+Math.random();
// 配置请求的超时设置
int timeout=1000*7;
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(timeout)
.setConnectTimeout(timeout)
.setSocketTimeout(timeout)
.build();
final HttpConfig config = HttpConfig.custom().headers(HttpHeader.custom().build(), true);
config.timeout(requestConfig);
// new Thread(new Runnable() {
// @Override
// public void run() {
// long t1 = System.currentTimeMillis();
// try {
// HttpClientUtil.get(config.url(url));
// long t2 = System.currentTimeMillis();
// System.err.println("2耗费:"+(t2-t1));
// HttpClientUtil.get(config.url(url2));
// long t3 = System.currentTimeMillis();
// System.err.println("3耗费:"+(t3-t1));
// } catch (HttpProcessException e) {
//// e.printStackTrace();
// System.err.println(e.getMessage());
// } finally {
// System.err.println("===finally===");
// }
// }
// }).start();
// new Thread(new Runnable() {
// @Override
// public void run() {
// long t1 = System.currentTimeMillis();
// try {
// HttpClientUtil.get(config.url(url));
// long t2 = System.currentTimeMillis();
// System.err.println("2耗费:"+(t2-t1));
// HttpClientUtil.get(config.url(url2));
// long t3 = System.currentTimeMillis();
// System.err.println("3耗费:"+(t3-t1));
// } catch (HttpProcessException e) {
//// e.printStackTrace();
// System.err.println(e.getMessage());
// } finally {
// System.err.println("===finally===");
// }
// }
// }).start();
// String result = HttpClientUtil.get(config);
// System.out.println(result);
// for (Header header : config.headers()) {
// System.out.println(header);
// }
//测试HttpResult返回方式
long t1 = System.currentTimeMillis();
HttpResult result = HttpClientUtil.sendAndGetResp(config.url(url));
long t2 = System.currentTimeMillis();
System.out.println("返回结果(内容太长,仅打印字节数):"+result.getResult().length());
System.out.println("状态码:"+result.getStatusCode());
System.out.println("使用协议:"+result.getProtocolVersion());
System.out.println("----------");
System.out.println("耗时:"+(t2-t1));
}
示例18
public static void main(String[] args) throws HttpProcessException {
//登录地址
String loginUrl = "https://passport.csdn.net/account/login";
//C币查询
String scoreUrl = "http://my.csdn.net/my/score";
HttpCookies cookies = HttpCookies.custom();
HttpConfig config =HttpConfig.custom().url(loginUrl).context(cookies.getContext());
//获取参数
String loginform = HttpClientUtil.get(config);//可以用.send(config)代替,但是推荐使用明确的get方法
//System.out.println(loginform);
// //打印参数,可以看到cookie里已经有值了。
// for (Cookie cookie : cookies.getCookieStore().getCookies()) {
// System.out.println(cookie.getName()+"--"+cookie.getValue());
// }
System.out.println("获取登录所需参数");
String lt = regex("\"lt\" value=\"([^\"]*)\"", loginform)[0];
String execution = regex("\"execution\" value=\"([^\"]*)\"", loginform)[0];
String _eventId = regex("\"_eventId\" value=\"([^\"]*)\"", loginform)[0];
//组装参数
Map<String, Object> map = new HashMap<String, Object>();
map.put("username", "用户名");
map.put("password", "密码");
map.put("lt", lt);
map.put("execution", execution);
map.put("_eventId", _eventId);
//发送登录请求
String result = HttpClientUtil.post(config.map(map));//可以用.send(config.method(HttpMethods.POST).map(map))代替,但是推荐使用明确的post方法
//System.out.println(result);
if(result.contains("帐号登录")){//如果有帐号登录,则说明未登录成功
String errmsg = regex("\"error-message\">([^<]*)<", result)[0];
System.err.println("登录失败:"+errmsg);
return;
}
System.out.println("----登录成功----");
// //打印参数,可以看到cookie里已经有值了。
for (Cookie cookie : cookies.getCookieStore().getCookies()) {
System.out.println(cookie.getName()+"--"+cookie.getValue());
}
//访问积分管理页面
Header[] headers = HttpHeader.custom().userAgent("User-Agent: Mozilla/5.0").build();
result = HttpClientUtil.post(config.url(scoreUrl).headers(headers));//可以用.send(config.url(scoreUrl).headers(headers))代替,但是推荐使用明确的post方法
//获取C币
String score = regex("\"last-img\"><span>([^<]*)<", result)[0];
System.out.println("您当前有C币:"+score);
}
示例19
public GetRunnable(CountDownLatch countDownLatch,HttpConfig config, String url){
this(countDownLatch, config, url, null);
}
示例20
public GetRunnable(CountDownLatch countDownLatch,HttpConfig config, String url, FileOutputStream out){
this.countDownLatch = countDownLatch;
this.config = config;
this.out = out;
this.url = url;
}
示例21
public static void main(String[] args) throws HttpProcessException {
//登录地址
String loginUrl = "https://passport.csdn.net/account/login";
//C币查询
String scoreUrl = "http://my.csdn.net/my/score";
//定义cookie存储
HttpClientContext context = new HttpClientContext();
CookieStore cookieStore = new BasicCookieStore();
context.setCookieStore(cookieStore);
HttpConfig config =HttpConfig.custom().url(loginUrl).context(context);
//获取参数
String loginform = HttpClientUtil.get(config);//可以用.send(config)代替,但是推荐使用明确的get方法
//System.out.println(loginform);
System.out.println("获取登录所需参数");
String lt = regex("\"lt\" value=\"([^\"]*)\"", loginform)[0];
String execution = regex("\"execution\" value=\"([^\"]*)\"", loginform)[0];
String _eventId = regex("\"_eventId\" value=\"([^\"]*)\"", loginform)[0];
//组装参数
Map<String, Object> map = new HashMap<String, Object>();
map.put("username", "用户名");
map.put("password", "密码");
map.put("lt", lt);
map.put("execution", execution);
map.put("_eventId", _eventId);
//发送登录请求
String result = HttpClientUtil.post(config.map(map));//可以用.send(config.method(HttpMethods.POST).map(map))代替,但是推荐使用明确的post方法
//System.out.println(result);
if(result.contains("帐号登录")){//如果有帐号登录,则说明未登录成功
String errmsg = regex("\"error-message\">([^<]*)<", result)[0];
System.err.println("登录失败:"+errmsg);
return;
}
System.out.println("----登录成功----");
// //打印参数,可以看到cookie里已经有值了。
// cookieStore = context.getCookieStore();
// for (Cookie cookie : cookieStore.getCookies()) {
// System.out.println(cookie.getName()+"--"+cookie.getValue());
// }
//访问积分管理页面
Header[] headers = HttpHeader.custom().userAgent("User-Agent: Mozilla/5.0").build();
result = HttpClientUtil.post(config.url(scoreUrl).headers(headers));//可以用.send(config.url(scoreUrl).headers(headers))代替,但是推荐使用明确的post方法
//获取C币
String score = regex("\"last-img\"><span>([^<]*)<", result)[0];
System.out.println("您当前有C币:"+score);
}
示例22
public GetRunnable setConfig(HttpConfig config){
this.config = config;
return this;
}
示例23
/**
* 下载文件
*
* @param config 请求参数配置
* @return 返回处理结果
* @throws HttpProcessException http处理异常
*/
public static OutputStream down(HttpConfig config) throws HttpProcessException {
if(config.method() == null) {
config.method(HttpMethods.GET);
}
return fmt2Stream(execute(config), config.out());
}
示例24
/**
* 上传文件
*
* @param config 请求参数配置
* @return 返回处理结果
* @throws HttpProcessException http处理异常
*/
public static String upload(HttpConfig config) throws HttpProcessException {
if(config.method() != HttpMethods.POST && config.method() != HttpMethods.PUT){
config.method(HttpMethods.POST);
}
return send(config);
}
示例25
/**
* 直接获取网络验证码(通过获取图片流,然后识别验证码)
*
* @param config HttpConfig对象(设置cookie)
* @param savePath 图片保存的完整路径(值为null时,不保存),如:c:/1.png
* @return 返回识别的验证码结果
*/
public static String ocrCode4Net(HttpConfig config, String savePath){
return ocrCode4Net(config, savePath, 0);
}
示例26
/**
* 直接获取网络验证码(通过获取图片流,然后识别验证码)
*
* @param config HttpConfig对象(设置cookie)
* @param savePath 图片保存的完整路径(值为null时,不保存),如:c:/1.png
* @return 返回识别的验证码结果
*/
public static String ocrCode4Net(HttpConfig config, String savePath){
return ocrCode4Net(config, savePath, 0);
}
示例27
/**
* 以Get方式,请求资源或服务
*
* @param client client对象
* @param url 资源地址
* @param headers 请求头信息
* @param context http上下文,用于cookie操作
* @param encoding 编码
* @return 返回处理结果
* @throws HttpProcessException http处理异常
*/
public static String get(HttpClient client, String url, Header[] headers, HttpContext context, String encoding) throws HttpProcessException {
return get(HttpConfig.custom().client(client).url(url).headers(headers).context(context).encoding(encoding));
}
示例28
/**
* 以Get方式,请求资源或服务
*
* @param config 请求参数配置
* @return 返回结果
* @throws HttpProcessException http处理异常
*/
public static String get(HttpConfig config) throws HttpProcessException {
return send(config.method(HttpMethods.GET));
}
示例29
/**
* 以Post方式,请求资源或服务
*
* @param client client对象
* @param url 资源地址
* @param headers 请求头信息
* @param parasMap 请求参数
* @param context http上下文,用于cookie操作
* @param encoding 编码
* @return 返回处理结果
* @throws HttpProcessException http处理异常
*/
public static String post(HttpClient client, String url, Header[] headers, Map<String,Object>parasMap, HttpContext context, String encoding) throws HttpProcessException {
return post(HttpConfig.custom().client(client).url(url).headers(headers).map(parasMap).context(context).encoding(encoding));
}
示例30
/**
* 以Post方式,请求资源或服务
*
* @param config 请求参数配置
* @return 返回处理结果
* @throws HttpProcessException http处理异常
*/
public static String post(HttpConfig config) throws HttpProcessException {
return send(config.method(HttpMethods.POST));
}