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(); } } }
相关文章推荐
- C++ 简单实现HTTP GET/POST 请求
- post/get请求(http,https)工具类
- Android----------OkHttp网络请求框架Get和Post简单封装(泛型)
- HttpUtil工具类get与post请求
- C++ 简单实现HTTP GET/POST 请求
- HttpClient发送Get、Post请求简单实践
- Http请求get、post工具类
- C# http请求相关的函数 HttpWebRequest: Post , Get ; PostAndRedirect
- Http请求get、post工具类
- 发送http-get,post请求工具类
- Vue------第五天(Vue的Ajax请求,使用Axios,目前熟悉了一下,主要包括GET请求、POST请求、并发请求、请求参数的配置、服务器响应的结构以及对服务器响应错误的简单处理)
- android HttpClient get请求与post请求工具类
- "Android下使用HttpUrlConntion"进行最简单的get,post请求(包括创建服务器)
- C++ 简单实现HTTP GET/POST 请求
- HttpClient(get/post)请求封装成工具类
- C#模拟http 发送post或get请求的简单实例
- java http请求的get和post方法工具类
- Qt HTTP网络相关GET,POST(HTTP 模拟POST 表单(multipartform)最简单和正式的方法)
- Http的get和post请求简单应用
- Java学习笔记———《http的get请求和post请求及封装的工具类》