您的位置:首页 > 理论基础 > 计算机网络

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: