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

HTTP请求工具类,完成简单的GET POST请求(为了熟悉相关API)。

2018-07-12 09:14 495 查看
HTTP请求工具类,完成简单的GET POST请求.代码很简单。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;

/**
* @author WangShiXiang
* @date 2018/7/10
**/
public class RequestHttp {

Logger LOG= LoggerFactory.getLogger(RequestHttp.class);

private String urlStr=null;

private HttpURLConnection connection=null;

private Map<String,String> cookie=null;

private Map<String,String> param=null;

private Map<String,String> header=null;

private String body=null;

private String result=null;

private int connectTimeOut=30000;

private int readTimeOut=30000;

private int code=-1;

public static final int SUCCESS_CODE=200;

private String charSetName="UTF-8";

private String errorMessage=null;

/**
* 总共请求几次,设置3就是网络不好时总共请求3次
* 默认请求1次 不重试
*/
private int retry=1;

public static RequestHttp buidRequest(String urlStr){

return new RequestHttp(urlStr);
}

private RequestHttp(String urlStr){
this.urlStr=urlStr;
}

public RequestHttp setParam(String key,String value){
if (param==null){
param=new HashMap<>(16);
}
param.put(key,value);
return this;
}

public RequestHttp setCookie(String key,String value){
if (cookie==null){
cookie=new HashMap<>(16);
}
cookie.put(key,value);
return this;
}

public RequestHttp setHeader(String key,String value){
if (header==null){
header=new HashMap<>(16);
}
header.put(key,value);
return this;
}

public String getResult(){
return result;
}

public int getResponseCode(){
return code;
}

public RequestHttp setConnectTimeOut(int connectTimeOut) {
this.connectTimeOut = connectTimeOut;
return this;
}

public RequestHttp setReadTimeOut(int readTimeOut) {
this.readTimeOut = readTimeOut;
return this;
}

public String getErrorMessage() {
return errorMessage;
}
public RequestHttp post(){
for(int i=0;i<retry;i++){
try {
postP();
}catch (SocketException e){
LOG.info("第{}次请求失败,请求url为:{}",i+1,urlStr);
if (i==retry-1){
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
return this;
}
}

return this;
}

private void postP() throws IOException {
URL url=null;
try {
url=new URL(urlStr);
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (url==null){
throw new MalformedURLException("生成的url为null");
}
try {
connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(connectTimeOut);
connection.setReadTimeout(readTimeOut);
setCookie();
setHeader();
setParam(false);
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStream outputStream=connection.getOutputStream();
DataOutputStream dataOutputStream=new DataOutputStream(outputStream);
dataOutputStream.writeBytes(body);
dataOutputStream.flush();
resolverConnection();
} catch (IOException e) {
throw e;
}
}
public RequestHttp get(){
for(int i=0;i<retry;i++){
try {
getP();
}catch (SocketException e){
LOG.info("第{}次请求失败,请求url为:{}",i+1,urlStr);
if (i==retry-1){
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
return this;
}
}

return this;
}
private RequestHttp getP() throws IOException {
URL url=null;
setParam(true);
setCookie();
try {
url=new URL(urlStr);
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (url==null){
return this;
}
try {
connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(connectTimeOut);
connection.setReadTimeout(readTimeOut);
setCookie();
setHeader();
resolverConnection();
} catch (IOException e) {
throw e;
}

return this;
}

private void setHeader(){
if (header!=null){
header.keySet().forEach(key->{connection.setRequestProperty(key,header.get(key));});
}
}
private void setCookie(){
if (cookie!=null){
StringBuilder sb =new StringBuilder();
cookie.keySet().forEach(key->{sb.append(key).append("=").append(cookie.get(key));});
connection.setRequestProperty("Cookie", sb.toString());
}
}
private void setParam(boolean ifGet){
if (param!=null&&body==null){
StringBuilder sb=new StringBuilder();
if (ifGet){
sb.append(urlStr).append("?");
}
param.keySet().forEach(key->{
sb.append(key).append("=").append(param.get(key)).append("&");
});
if (ifGet){
urlStr=sb.toString();
}else {
body=sb.toString();
}
}
}

public RequestHttp setBody(String body) {
if (param==null) {
this.body = body;
}
return this;
}

/**
* 用来设置重试次数
* @param retry 重试次数
* @return 返回RequestHttp
*/
public RequestHttp setRetry(int retry) {
this.retry = retry;
return this;
}

/**
* 请求后用来解析数据
* @throws IOException
*/
private void resolverConnection() throws IOException {
if (connection.getResponseCode()==SUCCESS_CODE) {
code=SUCCESS_CODE;
InputStream inputStream=connection.getInputStream();
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
byte[] buf=new byte[1024];
int count;
while((count=inputStream.read(buf))!=-1) {
outputStream.write(buf, 0, count);
}
result=outputStream.toString(charSetName);
}else {
InputStream inputStream=connection.getErrorStream();
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
byte[] buf=new byte[1024];
int count;
while((count=inputStream.read(buf))!=-1) {
outputStream.write(buf, 0, count);
}
errorMessage=outputStream.toString(charSetName);
code=connection.getResponseCode();
}
}

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