代码案例:package com.what21.http.client4_5;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class What21ClientWithGet {
public final static void main(String[] args) throws Exception {
// 创建HTTPClient
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet("http://www.what21.com");
System.out.println("执行请求:" + httpget.getURI());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
System.out.println("----------------------------------------");
System.out.println("返回响应: " + response.getStatusLine());
System.out.println("响应内容:" + EntityUtils.toString(response.getEntity()));
System.out.println("----------------------------------------");
httpget.abort();
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}package com.what21.http.client4_5;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class What21ClientWithPost {
public final static void main(String[] args) throws Exception {
// 创建HTTPClient
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://www.what21.com/");
System.out.println("执行请求:" + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println("返回响应: " + response.getStatusLine());
System.out.println("响应内容:" + EntityUtils.toString(response.getEntity()));
System.out.println("----------------------------------------");
// 终止
httppost.abort();
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}