版权声明:转载请注明出处哦 https://blog.csdn.net/k99sam/article/details/83819164
原料:
MAVEN导入
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
例1:Get网页并存盘
CloseableHttpClient defaultHttpClient = HttpClients.createDefault();
HttpGet hg = new HttpGet("http://www.k99sam.com/photos/list");
//设置cookie
hg.setHeader("cookie", "t=ea927b137ec52d665a842efa2e5eb5bc9; path=/; domain=.k99sam.com; Expires=Tue, 19 Jan 2038 03:14:07 GMT;");
HttpResponse httpResponse = defaultHttpClient.execute(hg);
File f1 = new File("temp.html");
InputStream is = httpResponse.getEntity().getContent();
//这里用EntityUtils获得原始网页代码文本,HTTP.UTF_8已过时了,用StandardCharsets.UTF_8替代!
String srcHtml = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
FileOutputStream fos = new FileOutputStream(f1);
fos.write(srcHtml.getBytes());
fos.close();
例2:Get图片或文件资源
CloseableHttpClient defaultHttpClient = HttpClients.createDefault();
HttpGet hg = new HttpGet("http://www.k99sam.com/photos/yourwife.jpg");
hg.setHeader("cookie","t=ea927b137ec52d665a842efa2e5eb5bc9; path=/; domain=.k99sam.com; Expires=Tue, 19 Jan 2038 03:14:07 GMT;");
HttpResponse httpResponse = defaultHttpClient.execute(hg);
File f1 = new File("test.jpg");
InputStream is = httpResponse.getEntity().getContent();
FileOutputStream fos = new FileOutputStream(f1);
byte[] buf = new byte[1024 * 1024];
int size;
while ((size = is.read(buf)) != -1){
fos.write(buf,0,size);
}
fos.close();
is.close();
hg.releaseConnection();
例3:发送Post请求
CloseableHttpClient defaultHttpClient = HttpClients.createDefault();
//用BasicNameValuePair制作参数
List<BasicNameValuePair> paramList = new ArrayList<>();
paramList.add(new BasicNameValuePair("username","k99sam"));
paramList.add(new BasicNameValuePair("password","123456"));
HttpPost hp = new HttpPost("http://www.k99sam.com/addUser");
//参数实体,注意编码!
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(paramList,StandardCharsets.UTF_8);
hp.setHeader("cookie","t=ea927b137ec52d665a842efa2e5eb5bc9; path=/; domain=.k99sam.com; Expires=Tue, 19 Jan 2038 03:14:07 GMT;");
//设置body的实体
hp.setEntity(urlEncodedFormEntity);
HttpResponse httpResponse = defaultHttpClient.execute(hp);
if (httpResponse.getStatusLine().getStatusCode() == 200){
//do something....
}
hp.releaseConnection();