目录
1、通过HttpURLConnection发送GET和POST请求
2、通过Apache HttpClient发送GET和POST请求
1、通过HttpURLConnection发送GET和POST请求
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionDemo {
public String doPost(String URL){
OutputStreamWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
HttpURLConnection conn = null;
try{
URL url = new URL(URL);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
//发送POST请求必须设置为true
conn.setDoOutput(true);
conn.setDoInput(true);
//设置连接超时时间和读取超时时间
conn.setConnectTimeout(30000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
//获取输出流
out = new OutputStreamWriter(conn.getOutputStream());
//参数
String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Tim\"}";
out.write(jsonStr);
out.flush();
out.close();
//取得输入流,并使用Reader读取
if (200 == conn.getResponseCode()){
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null){
result.append(line);
System.out.println(line);
}
}else{
System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
}
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(out != null){
out.close();
}
if(in != null){
in.close();
}
}catch (IOException ioe){
ioe.printStackTrace();
}
}
return result.toString();
}
public String doGet(String URL){
HttpURLConnection conn = null;
InputStream is = null;
BufferedReader br = null;
StringBuilder result = new StringBuilder();
try{
//创建远程url连接对象
URL url = new URL(URL);
//通过远程url连接对象打开一个连接,强转成HTTPURLConnection类
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
//设置连接超时时间和读取超时时间
conn.setConnectTimeout(15000);
conn.setReadTimeout(60000);
conn.setRequestProperty("Accept", "application/json");
//发送请求
conn.connect();
//通过conn取得输入流,并使用Reader读取
if (200 == conn.getResponseCode()){
is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line;
while ((line = br.readLine()) != null){
result.append(line);
System.out.println(line);
}
}else{
System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
}
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(br != null){
br.close();
}
if(is != null){
is.close();
}
}catch (IOException ioe){
ioe.printStackTrace();
}
conn.disconnect();
}
return result.toString();
}
}
2、通过Apache HttpClient发送GET和POST请求
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
/**
* Created by chengxia on 2018/12/5.
*/
public class ApacheHttpClientDemo {
public String doGet(String url){
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try{
//通过默认配置创建一个httpClient实例
httpClient = HttpClients.createDefault();
//创建httpGet远程连接实例
HttpGet httpGet = new HttpGet(url);
//httpGet.addHeader("Connection", "keep-alive");
//设置请求头信息
httpGet.addHeader("Accept", "application/json");
//配置请求参数
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(35000) //设置连接主机服务超时时间
.setConnectionRequestTimeout(35000)//设置请求超时时间
.setSocketTimeout(60000)//设置数据读取超时时间
.build();
//为httpGet实例设置配置
httpGet.setConfig(requestConfig);
//执行get请求得到返回对象
response = httpClient.execute(httpGet);
//通过返回对象获取返回数据
HttpEntity entity = response.getEntity();
//通过EntityUtils中的toString方法将结果转换为字符串,后续根据需要处理对应的reponse code
result = EntityUtils.toString(entity);
System.out.println(result);
}catch (ClientProtocolException e){
e.printStackTrace();
}catch (IOException ioe){
ioe.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally {
//关闭资源
if(response != null){
try {
response.close();
}catch (IOException ioe){
ioe.printStackTrace();
}
}
if(httpClient != null){
try{
httpClient.close();
}catch (IOException ioe){
ioe.printStackTrace();
}
}
}
return result;
}
public String doPost(String url){
//创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String result = "";
try{
//创建http请求
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
//创建请求内容
String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Tim\"}";
StringEntity entity = new StringEntity(jsonStr);
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
}catch (Exception e){
e.printStackTrace();
}finally {
//关闭资源
if(response != null){
try {
response.close();
}catch (IOException ioe){
ioe.printStackTrace();
}
}
if(httpClient != null){
try{
httpClient.close();
}catch (IOException ioe){
ioe.printStackTrace();
}
}
}
return result;
}
}