apache HttpClient和HttpURLConnection发送get请求和post请求
apache HttpClient和HttpURLConnection发送get请求和post请求
本文主要介绍如题的两种方式下,如何发送http的get和post请求。
apache HttpClient
package com.xueyou.http;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class HttpClient {
public static final String GET_URL = "http://www.baidu.com";
public static final String POST_URL = "http://www.baidu.com";
public static void main(String[] args) throws Exception {
getRequest();
postRequest();
}
/**
* post方式提交json代码
*
* @throws Exception
*/
public static void getRequest() throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建httpget.
HttpGet httpget = new HttpGet(GET_URL);
System.out.println("executing request " + httpget.getURI());
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 打印响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印响应内容长度
System.out.println("Response content length: " + entity.getContentLength());
// 打印响应内容
System.out.println("Response content: " + EntityUtils.toString(entity));
}
System.out.println("------------------------------------");
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 发送 post请求访问本地应用并根据传递参数不同返回不同结果
*/
public static void postRequest() {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(POST_URL);
// 创建参数队列
List formparams = new ArrayList();
formparams.add(new BasicNameValuePair("name", "xiaoming"));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("--------------------------------------");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("--------------------------------------");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
HttpURLConnection方式
package com.xueyou.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
public class URLConnectionClient {
private final static String HTTP_URL_GET = "http://www.baidu.com";
private final static String HTTP_URL_POST = "http://www.baidu.com";
private static HashMap<String, String> mData = new HashMap<String, String>();
public static void main(String[] args) throws Exception {
mData.put("name", "HongBin");
mData.put("sex", "male");
System.out.println("GetResult:" + startGet(HTTP_URL_GET));
System.out.println("PostResult:" + startPost(HTTP_URL_POST));
}
private static String startGet(String path) {
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
//GET请求直接在链接后面拼上请求参数
String mPath = path + "?";
for (String key : mData.keySet()) {
mPath += key + "=" + mData.get(key) + "&";
}
mPath = mPath.substring(0, mPath.length() - 1);
URL url = new URL(mPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
//Get请求不需要DoOutPut
conn.setDoOutput(false);
conn.setDoInput(true);
//设置连接超时时间和读取超时时间
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
// String routeCode = conn.getRequestProperty("routeCode");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//连接服务器
conn.connect();
// 取得输入流,并使用Reader读取
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
//关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result.toString();
}
private static String startPost(String path) {
OutputStreamWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// 发送POST请求必须设置为true
conn.setDoOutput(true);
conn.setDoInput(true);
//设置连接超时时间和读取超时时间
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Content-Type", "x-www-form-urlencoded");
out = new OutputStreamWriter(conn.getOutputStream());
// POST的请求参数写在正文中
for (String key : mData.keySet()) {
out.write(key + "=" + mData.get(key) + "&");
}
out.flush();
out.close();
// 取得输入流,并使用Reader读取
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
//关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result.toString();
}
}
还没有评论,来说两句吧...