http请求的实现方法
2017-06-15 00:00
169 查看
package com.oppo.browser.http; import com.oppo.browser.common.Logger; import org.json.JSONException; import org.json.JSONObject; import javax.net.ssl.HttpsURLConnection; import java.io.*; import java.net.HttpURLConnection; import java.util.Iterator; import java.util.Map; public class Requests { /** * 向指定URL发送GET方法的请求 * * @author bony * @param url 发送请求的URL * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return URL 所代表远程资源的响应结果 */ Logger logger = Logger.getLogger(Requests.class); public boolean IS_PROXY = false;//是否代理 public String PROXY_HOST = null;//代理地址 public int PROXY_PROT = 0;//是否端口 public Map<String, String> HRADER;//请求头 public String URL;//请求URL /** * 简化封装的get方法 * * @param url 链接/地址 * @param header 请求头 * @param parame JSONObject参数对象 * @param protocol 请求协议类型 HTTP/HTTPS * @return InputStream对象 */ private Response get(String url, Map<String, String> header, JSONObject parame, String protocol) { this.HRADER = header; logger.info("header >> " + this.HRADER.toString()); return Send("get", url, getUrlArgs(parame), null, protocol); } /** * 简化封装的post方法 * * @param url 链接/地址 * @param header 请求头 * @param parame JSONObject参数对象 * @param protocol 请求协议类型 HTTP/HTTPS * @return Response对象 */ private Response post(String url, Map<String, String> header, JSONObject parame, JSONObject body, String protocol) { this.HRADER = header; logger.info("header >> " + this.HRADER.toString()); return Send("post", url, getUrlArgs(parame), getUrlArgs(body), protocol); } /** * 简化封装的HttpsGet方法 * * @param url 链接/地址 * @param header 请求头 * @param parame JSONObject参数对象 * @return Response对象 */ public Response HttpsGet(String url, Map<String, String> header, JSONObject parame) { return get(url, header, parame, "https"); } /** * 简化封装的HttpGet方法 * * @param url 链接/地址 * @param header 请求头 * @param parame JSONObject参数对象 * @return Response对象 */ public Response HttpGet(String url, Map<String, String> header, JSONObject parame) { return get(url, header, parame, "http"); } /** * 简化封装的HttpsPost方法 * * @param url 链接/地址 * @param header 请求头 * @param parame JSONObject参数对象 * @return Response对象 */ public Response HttpsPost(String url, Map<String, String> header, JSONObject parame, JSONObject body) { return post(url, header, parame, body, "https"); } /** * 简化封装的HttpPost方法 * * @param url 链接/地址 * @param header 请求头 * @param parame JSONObject参数对象 * @return Responsem对象 */ public Response HttpPost(String url, Map<String, String> header, JSONObject parame, JSONObject body) { return post(url, header, parame, body, "http"); } public String getUrlArgs(JSONObject parame) { String parame_tmp = ""; if (parame != null && !parame.equals("")) { for (Iterator it = parame.keys(); it.hasNext(); ) { String key = (String) it.next(); try { if (parame.get(key) instanceof String) { parame_tmp += key + "=" + parame.get(key) + "&"; } else { // your code System.out.println(parame.get(key)); parame_tmp += key + "=" + parame.get(key) + "&"; } } catch (JSONException e) { e.printStackTrace(); } } } return parame_tmp; } /** * 请求方法 * * @param Type 请求属性 GET/POST * @param url 请求地址 * @param param 请求参数 * @param protocol 请求协议类型 HTTP/HTTPS * @return Response对象 */ private Response Send(String Type, String url, String param, String body, String protocol) { Response response = new Response(); try { if (param != null && !param.equals("")) URL = url + "?" + param; else URL = url; logger.info("url >> " + this.URL); if (protocol.equals("http")) { HttpConnection httpConnection = new HttpConnection(); if (IS_PROXY == true) httpConnection.setProxy(PROXY_HOST, PROXY_PROT); HttpURLConnection Connection = httpConnection.getHttpConnection(URL); Connection.setConnectTimeout(1500);//设置链连接超时 Connection.setReadTimeout(1500);//设置读超时 Iterator<Map.Entry<String, String>> entries = this.HRADER.entrySet().iterator(); System.out.println(this.HRADER); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); Connection.setRequestProperty(entry.getKey(), entry.getValue()); } if (Type.equals("post")) { Connection.setDoOutput(true);//设置输出 Connection.setDoInput(true);//设置输入 } Connection.connect();//建立连接 if (Type.equals("post")) { OutputStream output_stream = Connection.getOutputStream();//得到输出流 PrintWriter print_writer = new PrintWriter(output_stream);//创建输出流对象 print_writer.print(body); print_writer.flush();// flush输出流的缓冲 } response.CODE = Connection.getResponseCode();//得到响应代码 logger.info("Response code >> " + response.CODE); response.MESSAGE = Connection.getResponseMessage();//回应信息 logger.info("Response Message >> " + response.MESSAGE); response.InputStream = Connection.getInputStream();//创建输入流对象 ByteArrayOutputStream bytearrayoutputstream = Read(response.InputStream); response.CONTENT = bytearrayoutputstream.toByteArray(); response.TEXT = bytearrayoutputstream.toString(); } else if (protocol.equals("https")) { HttpsURLConnection Connection = new HttpConnection().getHttpsConnection(URL); Connection.setConnectTimeout(1500);//设置链连接超时 Connection.setReadTimeout(1500);//设置读超时 Iterator<Map.Entry<String, String>> entries = this.HRADER.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); Connection.setRequestProperty(entry.getKey(), entry.getValue()); } if (Type.equals("post")) { Connection.setDoOutput(true);//设置输出 Connection.setDoInput(true);//设置输入 } Connection.connect();//建立连接 if (Type.equals("post")) { OutputStream output_stream = Connection.getOutputStream();//得到输出流 PrintWriter print_writer = new PrintWriter(output_stream);//创建输出流对象 print_writer.print(body); print_writer.flush();// flush输出流的缓冲 } response.CODE = Connection.getResponseCode();//得到响应代码 logger.info("Response code >> " + response.CODE); response.MESSAGE = Connection.getResponseMessage();//回应信息 logger.info("Response Message >> " + response.MESSAGE); response.InputStream = Connection.getInputStream();//创建输入流对象 ByteArrayOutputStream bytearrayoutputstream = Read(response.InputStream); response.CONTENT = bytearrayoutputstream.toByteArray(); response.TEXT = bytearrayoutputstream.toString(); } else { System.out.println("Is Protocol Exception: " + protocol); } } catch (Exception e) { System.err.println(e.getMessage()); } return response; } /** * http请求返回流的读取 * * @return */ public ByteArrayOutputStream Read(InputStream content) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; try { while (-1 != (len = content.read(buffer))) { baos.write(buffer, 0, len); baos.flush(); } return baos; } catch (IOException e) { e.printStackTrace(); return baos; } } }
package com.oppo.browser.http; import javax.net.ssl.SSLEngine; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * * 先定义个trust定制类,证书信任管理器(用于https请求) * Created by 80071482 on 2017-05-26. */ class BZX509TrustManager implements TrustManager, X509TrustManager { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public boolean isServerTrusted( java.security.cert.X509Certificate[] certs) { return true; } public boolean isClientTrusted( java.security.cert.X509Certificate[] certs) { return true; } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType,SSLEngine e) throws java.security.cert.CertificateException { return; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return; } }
package com.oppo.browser.http; import javax.net.ssl.*; import java.net.*; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; /** * Created by 80071482 on 2017-05-26. */ public class HttpConnection { private boolean IS_PROXY = false;//是否代理 private String PROXY_HOST = null;//代理地址 private int PROXY_PROT = 80;//是否端口 /** * 设置代理 * @param host 代理地址 * @param prot 代理端口 */ public void setProxy(String host,int prot){ this.IS_PROXY = true; this.PROXY_HOST = host; this.PROXY_PROT = prot; } /** * 去除代理 */ public void removProxy(){ this.IS_PROXY = false; } public SSLSocketFactory getSSFactory() throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession sslsession) { return true; } }); TrustManager[] trustAllCerts = new TrustManager[1]; TrustManager tm = new BZX509TrustManager(); trustAllCerts[0] = tm; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, null); SSLSocketFactory ssf = sslContext.getSocketFactory(); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); return ssf; } public HttpsURLConnection getHttpsConnection(String url) throws Exception{ URL _url = new URL(url); SSLSocketFactory ssf= getSSFactory(); HttpsURLConnection Connection; if (IS_PROXY == true) { System.out.println("我在这里设置代理!"); Connection = (HttpsURLConnection) _url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, PROXY_PROT)));// 打开和URL之间的连接 } else { Connection = (HttpsURLConnection)_url.openConnection();// 打开和URL之间的连接 } Connection.setSSLSocketFactory(ssf); return Connection; } public HttpURLConnection getHttpConnection(String url) throws Exception{ URL _url = new URL(url); HttpURLConnection Connection; if (IS_PROXY == true) { Connection = (HttpURLConnection)_url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, PROXY_PROT)));// 打开和URL之间的连接 } else { Connection = (HttpURLConnection)_url.openConnection();// 打开和URL之间的连接 } return Connection; } }
package com.oppo.browser.http; import java.io.InputStream; /** * Created by 80071482 on 2017-05-11. */ public class Response { public InputStream InputStream; public byte[] CONTENT; public String TEXT; public String MESSAGE; public int CODE; }
相关文章推荐
- php之curl实现http与https请求的方法
- http的get、post请求实现方法
- PHP实现模拟http请求的方法分析
- HttpServletResponse.sendRedirect方法实现的请求重定向与RequestDispatcher.forward方法实现的请求转发的总结比较
- C# 实现http不同方法的请求
- php之curl实现http与https请求的方法
- Android HTTP实例 使用GET方法和POST方法发送请求(通过Apache接口实现)
- httpPost请求用java代码实现的方法
- spring cloud 之 Feign 使用HTTP请求远程服务的实现方法
- java使用common-httpclient包实现post请求方法示例
- android实现http中请求访问添加cookie的方法
- curl实现HTTP的GET POST方法的请求
- php之curl实现http与https请求的方法
- php之curl实现http与https请求的方法
- Android开发 httpClient post方法请求tomcat服务器实现注册登陆
- php之curl实现http与https请求的方法
- Angularjs中$http以post请求通过消息体传递参数的实现方法
- java遍历http请求request的所有参数实现方法
- 实例详解C#实现http不同方法的请求
- Httpclient 实现https请求,绕过SSL 方法