42 Star 131 Fork 53

icecooly / FastHttpClient

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

FastHttpClient

封装OkHttp3

  • 支持多线程异步请求
  • 支持Http/Https协议
  • 支持同步/异步请求
  • 支持异步延迟执行
  • 支持Cookie持久化
  • 支持JSON、表单提交
  • 支持文件和图片上传/批量上传,支持同步/异步上传,支持进度提示
  • 支持文件流上传

Download

Download Jar or grab via Maven:

<dependency>
  <groupId>com.github.icecooly</groupId>
  <artifactId>FastHttpClient</artifactId>
  <version>1.7</version>
</dependency>

or Gradle:

compile 'com.github.icecooly:FastHttpClient:1.7'

简单的例子

1.同步Get请求(访问百度首页,自动处理https单向认证)

String url="https://www.baidu.com";
String resp=FastHttpClient.get().url(url).build().execute().string();

2.异步Get请求(访问百度首页)

FastHttpClient.get().url("https://www.baidu.com").build().
	executeAsync(new StringCallback() {
		@Override
		public void onFailure(Call call, Exception e, int id) {
			logger.error(e.getMessage(),e);
		}
		@Override
		public void onSuccess(Call call, String response, int id) {
			logger.info("response:{}",response);
		}
	});

3.百度搜索关键字'微信机器人'

String html = FastHttpClient.get().
				url("http://www.baidu.com/s").
				addParams("wd", "微信机器人").
				addParams("tn", "baidu").
				build().
				execute().
				string();

4.异步下载一张百度图片,有下载进度,保存为/tmp/tmp.jpg

String savePath="tmp.jpg";
String imageUrl="http://e.hiphotos.baidu.com/image/pic/item/faedab64034f78f0b31a05a671310a55b3191c55.jpg";
FastHttpClient.newBuilder().addNetworkInterceptor(new DownloadFileInterceptor(){
			@Override
			public void updateProgress(long downloadLenth, long totalLength, boolean isFinish) {
				logger.info("updateProgress downloadLenth:"+downloadLenth+
						",totalLength:"+totalLength+",isFinish:"+isFinish);
			}
		}).
		build().
		get().
		url(imageUrl).
		build().
		executeAsync(new DownloadFileCallback(savePath) {//save file to /tmp/tmp.jpg
				@Override
				public void onFailure(Call call, Exception e, int id) {
					logger.error(e.getMessage(),e);
				}
				@Override
				public void onSuccess(Call call, File file, int id) {
					logger.info("filePath:"+file.getAbsolutePath());
				}
				@Override
				public void onSuccess(Call call, InputStream fileStream, int id) {
					logger.info("onSuccessWithInputStream");
				}
});

5.同步下载文件

public void testSyncDownloadFile() throws Exception{
	String savePath="tmp.jpg";
	String imageUrl="http://e.hiphotos.baidu.com/image/pic/item/faedab64034f78f0b31a05a671310a55b3191c55.jpg";
	InputStream is=FastHttpClient.get().url(imageUrl).build().execute().byteStream();
	FileUtil.saveContent(is, new File(savePath));
}

6.上传文件

byte[] imageContent=FileUtil.getBytes("/tmp/test.png");
		response = FastHttpClient.post().
				url(url).
				addFile("file", "b.jpg", imageContent).
				build().
				connTimeOut(10000).
				execute();
System.out.println(response.body().string());

7.上传文件(通过文件流)

InputStream is=new FileInputStream("/tmp/logo.jpg");
Response response = FastHttpClient.newBuilder().
		connectTimeout(10, TimeUnit.SECONDS).
		build().
		post().
		url("上传地址").
		addFile("file", "logo.jpg",is).
		build().
		execute();
logger.info(response.body().string());

8.设置网络代理

Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 1088));
Authenticator.setDefault(new Authenticator(){//如果没有设置账号密码,则可以注释掉这块
	         private PasswordAuthentication authentication = 
	         		new PasswordAuthentication("username","password".toCharArray());
	         @Override
	         protected PasswordAuthentication getPasswordAuthentication(){
	             return authentication;
	         }
	     });
Response response = FastHttpClient.
		newBuilder().
		proxy(proxy).
		build().
		get().
		url("http://ip111.cn/").
		build().
		execute();
logger.info(response.string());

9.设置Http头部信息

String url="https://www.baidu.com";
Response response=FastHttpClient.
			get().
			addHeader("Referer","http://news.baidu.com/").
			addHeader("cookie", "uin=test;skey=111111;").
			url(url).
			build().
			execute();
System.out.println(response.string());

9.设置https证书

SSLContext sslContext=getxxx();
Response response=FastHttpClient.
			get().
			sslContext(sslContext).
			url(url).
			build().
			execute();
System.out.println(response.string());

10.自动携带Cookie进行请求

private class LocalCookieJar implements CookieJar{
	    List<Cookie> cookies;
	    @Override
	    public List<Cookie> loadForRequest(HttpUrl arg0) {
	         if (cookies != null) {
	                return cookies;
	         }
	         return new ArrayList<Cookie>();
	    }
	    @Override
	    public void saveFromResponse(HttpUrl arg0, List<Cookie> cookies) {
	        this.cookies = cookies;
	    }
}
LocalCookieJar cookie=new LocalCookieJar();
HttpClient client=FastHttpClient.newBuilder()
        .followRedirects(false) //禁制OkHttp的重定向操作,我们自己处理重定向
        .followSslRedirects(false)
        .cookieJar(cookie)   //为OkHttp设置自动携带Cookie的功能
        .build();
String url="https://www.baidu.com/";
client.get().addHeader("Referer","https://www.baidu.com/").
	url(url).
	build().
	execute();
System.out.println(cookie.cookies);

11.设置Content-Type为application/json

String url="https://wx.qq.com";
Response response=FastHttpClient.
		post().
		addHeader("Content-Type","application/json").
		body("{\"username\":\"test\",\"password\":\"111111\"}").
		url(url).
		build().
		execute();

12.取消请求

RequestCall call=FastHttpClient.get().
				url("https://www.baidu.com").
				build();
Response response=call.execute();
call.cancel();
System.out.println(response.string());

13.取消所有请求

FastHttpClient.cancelAll();

14.按照TAG取消请求

FastHttpClient.cancel(tag);
MIT License Copyright (c) 2021 icecooly Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

封装OkHttp3,对外提供了POST请求、GET请求、PUT请求、上传文件、下载文件、https请求、cookie管理等功能 展开 收起
Java
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/icecooly/FastHttpClient.git
git@gitee.com:icecooly/FastHttpClient.git
icecooly
FastHttpClient
FastHttpClient
master

搜索帮助

14c37bed 8189591 565d56ea 8189591