【Java】【20】后台发送GET/POST方法

前言:html

1,get请求java

2,post请求node

3,post,get通用方法apache

4,其余的get,post写法json

通过一段时间的检验,用方法3吧,比较好用。app

 

【Java】【29】post,get通用方法增强 - 花生喂龙 - 博客园
https://www.cnblogs.com/huashengweilong/p/11028200.htmldom

 

正文:post

1,get请求ui

import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; // HTTP GET request
public static String SendGet(String url) { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.error("获取SendGet失败:" + method.getStatusLine()); } return method.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 static String SendPOST(String url) { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.error("获取SendPOST失败:" + method.getStatusLine()); } return method.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

import net.sf.json.JSONObject; import java.io.*; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.URL; //post,get通用方法
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { URL url= new URL(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 = new BufferedReader(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); } return jsonObject; }

https的请求方法,大同小异

import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; //post,get通用方法
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { //建立SSLContext对象,并使用咱们指定的信任管理器初始化 
        TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); //从上述SSLContext对象中获得SSLSocketFactory对象 
        SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(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 = new BufferedReader(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); } return jsonObject; } 
MyX509TrustManager.class
import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; /** * 证书信任管理器(用于https请求) * */  
public class MyX509TrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } } 

4,其余的get,post写法

/** * 向指定URL发送GET方法的请求 * * @param url * 发送请求的URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return URL 所表明远程资源的响应结果 */
    public static String sendGet(String url, String param) { String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打开和URL之间的链接
            URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); // 创建实际的链接
 connection.connect(); // 获取全部响应头字段
            Map<String, List<String>> map = connection.getHeaderFields(); // 遍历全部的响应头字段
            for (String key : map.keySet()) { map.get(key); } // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader( 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(); } } return result; }

 

/** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所表明远程资源的响应结果 */
    public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(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 = new BufferedReader( new InputStreamReader(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(); } } return result; }

参考博客:

1,JAVA利用HttpClient进行HTTPS接口调用 - 路常有 - 博客园
https://www.cnblogs.com/luchangyou/p/6375166.html

2,使用httpclient实现后台java发送post和get请求 - myrui422的博客 - CSDN博客
https://blog.csdn.net/mhqyr422/article/details/79787518

3,Java发送http get/post请求,调用接口/方法 - 向前爬的蜗牛 - 博客园

https://www.cnblogs.com/wdpnodecodes/p/7807027.html

相关文章
相关标签/搜索