前言:
经过一段时间的检验,用方法3吧,比较好用。
正文:
1,get请求
importorg.apache.commons.httpclient.HttpClient;importorg.apache.commons.httpclient.HttpException;importorg.apache.commons.httpclient.HttpStatus;importorg.apache.commons.httpclient.methods.GetMethod;importorg.apache.commons.httpclient.methods.PostMethod;//HTTP GET request
public staticString SendGet(String url) {
HttpClient client= newHttpClient();
GetMethod method= newGetMethod(url);try{int statusCode =client.executeMethod(method);if (statusCode !=HttpStatus.SC_OK) {
logger.error("获取SendGet失败:" +method.getStatusLine());
}returnmethod.getResponseBodyAsString();
}catch(HttpException e) {
logger.error("获取SendGet失败: Fatal protocol violation", e);
}catch(IOException e) {
logger.error("获取SendGet失败: transport error", e);
}finally{
method.releaseConnection();
}return "";
}
2,post请求
//HTTP POST
public staticString SendPOST(String url) {
HttpClient client= newHttpClient();
PostMethod method= newPostMethod(url);try{int statusCode =client.executeMethod(method);if (statusCode !=HttpStatus.SC_OK) {
logger.error("获取SendPOST失败:" +method.getStatusLine());
}returnmethod.getResponseBodyAsString();
}catch(HttpException e) {
logger.error("获取SendPOST失败: Fatal protocol violation", e);
}catch(IOException e) {
logger.error("获取SendPOST失败: transport error", e);
}finally{
method.releaseConnection();
}return "";
}
3,post,get通用方法
(1)返回的是json格式数据。根据我的使用情况来看,如果返回的是list数据,是要用JSONArray格式接收的,如果是多参数,用JSONObject。现在接口一般都会返回请求状态和错误原因及数据,所以用JSONObject接收就可以了
(2)HttpURLConnection代表请求的是http的URL,如果是https,需要用HttpsURLConnection
importnet.sf.json.JSONObject;import java.io.*;importjava.net.ConnectException;importjava.net.HttpURLConnection;importjava.net.URL;//post,get通用方法
public staticJSONObject httpRequest(String requestUrl, String requestMethod, String outputStr)
{
JSONObject jsonObject= null;
StringBuffer buffer= newStringBuffer();try{
URL url= newURL(requestUrl);
HttpURLConnection httpUrlConn=(HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);//设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();//当有数据需要提交时
if (null !=outputStr) {
OutputStream outputStream=httpUrlConn.getOutputStream();//注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}//将返回的输入流转换成字符串
InputStream inputStream =httpUrlConn.getInputStream();
InputStreamReader inputStreamReader= new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader= newBufferedReader(inputStreamReader);
String str= null;while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();//释放资源
inputStream.close();
httpUrlConn.disconnect();
jsonObject=JSONObject.fromObject(buffer.toString());
}catch(ConnectException ce) {
logger.info("httpRequest: Weixin server connection timed out.");
}catch(Exception e) {
logger.info("httpRequest: error:{}" +e);
}returnjsonObject;
}
https的请求方法,大同小异
importjavax.net.ssl.HttpsURLConnection;importjavax.net.ssl.SSLContext;importjavax.net.ssl.SSLSocketFactory;importjavax.net.ssl.TrustManager;//post,get通用方法
public staticJSONObject httpRequest(String requestUrl, String requestMethod, String outputStr)
{
JSONObject jsonObject= null;
StringBuffer buffer= newStringBuffer();try{//创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { newMyX509TrustManager() };
SSLContext sslContext= SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, newjava.security.SecureRandom());//从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf =sslContext.getSocketFactory();
URL url= newURL(requestUrl);
HttpsURLConnection httpUrlConn=(HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);//设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();//当有数据需要提交时
if (null !=outputStr) {
OutputStream outputStream=httpUrlConn.getOutputStream();//注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}//将返回的输入流转换成字符串
InputStream inputStream =httpUrlConn.getInputStream();
InputStreamReader inputStreamReader= new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader= newBufferedReader(inputStreamReader);
String str= null;while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();//释放资源
inputStream.close();
inputStream= null;
httpUrlConn.disconnect();
jsonObject=JSONObject.fromObject(buffer.toString());
}catch(ConnectException ce) {
logger.info("httpRequest: Weixin server connection timed out.");
}catch(Exception e) {
logger.info("httpRequest: error:{}" +e);
}returnjsonObject;
}
MyX509TrustManager.class
importjava.security.cert.CertificateException;importjava.security.cert.X509Certificate;importjavax.net.ssl.X509TrustManager;/*** 证书信任管理器(用于https请求)
**/
public class MyX509TrustManager implementsX509TrustManager {public void checkClientTrusted(X509Certificate[] chain, String authType) throwsCertificateException {
}public void checkServerTrusted(X509Certificate[] chain, String authType) throwsCertificateException {
}publicX509Certificate[] getAcceptedIssuers() {return null;
}
}
4,其他的get,post写法
/*** 向指定URL发送GET方法的请求
*
*@paramurl
* 发送请求的URL
*@paramparam
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
*@returnURL 所代表远程资源的响应结果*/
public staticString sendGet(String url, String param)
{
String result= "";
BufferedReader in= null;try{
String urlNameString= url + "?" +param;
URL realUrl= newURL(urlNameString);//打开和URL之间的连接
URLConnection connection =realUrl.openConnection();//设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");//建立实际的连接
connection.connect();//获取所有响应头字段
Map> map =connection.getHeaderFields();//遍历所有的响应头字段
for(String key : map.keySet()) {
map.get(key);
}//定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(newInputStreamReader(
connection.getInputStream()));
String line;while ((line = in.readLine()) != null) {
result+=line;
}
}catch(Exception e) {
logger.info("发送GET请求出现异常:" +e);
e.printStackTrace();
}//使用finally块来关闭输入流
finally{try{if (in != null) {
in.close();
}
}catch(Exception e2) {
e2.printStackTrace();
}
}returnresult;
}
/*** 向指定 URL 发送POST方法的请求
*
*@paramurl
* 发送请求的 URL
*@paramparam
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
*@return所代表远程资源的响应结果*/
public staticString sendPost(String url, String param)
{
PrintWriter out= null;
BufferedReader in= null;
String result= "";try{
URL realUrl= newURL(url);//打开和URL之间的连接
URLConnection conn =realUrl.openConnection();//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");//发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);//获取URLConnection对象对应的输出流
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));//发送请求参数
out.print(param);//flush输出流的缓冲
out.flush();//定义BufferedReader输入流来读取URL的响应
in = newBufferedReader(newInputStreamReader(conn.getInputStream()));
String line;while ((line = in.readLine()) != null) {
result+=line;
}
}catch(Exception e) {
logger.info("发送 POST 请求出现异常:"+e);
e.printStackTrace();
}//使用finally块来关闭输出流、输入流
finally{try{if(out!=null){
out.close();
}if(in!=null){
in.close();
}
}catch(IOException ex){
ex.printStackTrace();
}
}returnresult;
}
参考博客:
2,使用httpclient实现后台java发送post和get请求 - myrui422的博客 - CSDN博客
3,Java发送http get/post请求,调用接口/方法 - 向前爬的蜗牛 - 博客园