HttpKit2类

package com.cst.kit.http;`

`import java.io.BufferedReader;`
`import java.io.ByteArrayInputStream;`
`import java.io.ByteArrayOutputStream;`
`import java.io.DataOutputStream;`
`import java.io.File;`
`import java.io.FileInputStream;`
`import java.io.InputStream;`
`import java.io.InputStreamReader;`
`import java.net.HttpURLConnection;`
`import java.net.URL;`
`import java.net.URLEncoder;`
`import java.nio.charset.Charset;`
`import java.util.*;`
`import java.util.stream.Collectors;`

`import com.cst.kit.string.CharsetKit;`
`import com.cst.kit.string.Joiner;`
`import com.cst.kit.string.JsonKit;`
`import com.cst.kit.string.StringKit;`

`/**`

 * `@author guweichao`

 * `@created 2020-9-7`

 * `@desc 1. header param getUrl|postUrl(不限定顺序) 三个方法,指定需要的请求参数 <br>`

 * `2.doHttp 执行请求,返回true 或 false <br>`

 * `3.使用 getResultList 或 getResultSteam 或 getResultString 获取结果(推荐`

 * `getResultList,原始结果,其他两个需要数据转化 )`
    `*/`
   `public class HttpKit2 {`

   `private int timeout;`
   `private String url;`
   `private String method;`
   `private Map<String, Object> params = null;`
   `private Map<String, String> headers = null;`
   `private Map<String, String> requestProperties = null;`
   `private Map<String, File> uploads = null;`
   `private Object body;`

   `private String resultString;`
   `private List<String> resultList;`
   `private InputStream resultStream;`
   `private ByteArrayOutputStream baos;`
   `private Exception exception;`

   `private String boundary = "***cstHttpClientBoundary***";`
   `private String end = "\r\n";`
   `private String prefix = "--";`

   `public HttpKit2() {`
   	`this(15000);`
   `}`

   `public HttpKit2(int timeout) {`
   	`this.timeout = timeout;`
   `}`

   `/**`

    * `@author guweichao`
    * `@created_at 2020-9-17 14:17:45`
    * `@return 当访问失败时,获取实际抛出的异常(也可以通过 getResult 获取 异常中的信息)`
      `*/`
      `public Exception getException() {`
      `return exception;`
      `}`

   `public InputStream getResultStream() {`
   	`if (baos == null) {`
   		`return null;`
   	`}`
   	`this.resultStream = new ByteArrayInputStream(baos.toByteArray());`
   	`return this.resultStream;`
   `}`

   `public String getResultString() {`
   	`if (resultString == null) {`
   		`return getResultString(CharsetKit.UTF8());`
   	`}`
   	`return resultString;`
   `}`

   `public String getResultString(Charset charset) {`
   	`if (resultString == null) {`
   		`InputStream in = getResultStream();`
   		`if (in == null) {`
   			`return null;`
   		`}`
   		`BufferedReader br;`
   		`br = new BufferedReader(new InputStreamReader(in, charset));`
   		`this.resultList = br.lines().collect(Collectors.toList());`
   		`resultString = StringKit.of(resultList);`
   	`}`
   	`return resultString;`
   `}`

   `public List<String> getResultList() {`
   	`if (resultList == null) {`
   		`getResultString();`
   	`}`
   	`return resultList;`
   `}`

   `public HttpKit2 requestProperty(String key, String value) {`
   	`if (requestProperties == null) {`
   		`requestProperties = new HashMap<>();`
   	`}`
   	`requestProperties.put(key, value);`
   	`return this;`
   `}`

   `public HttpKit2 header(String key, String value) {`
   	`if (headers == null) {`
   		`headers = new HashMap<>();`
   	`}`
   	`headers.put(key, value);`
   	`return this;`
   `}`

   `public HttpKit2 header(Map<String, String> headers) {`
   	`if (headers == null || headers.isEmpty()) {`
   		`return this;`
   	`}`
   	`if (this.headers == null || this.headers.isEmpty()) {`
   		`this.headers = headers;`
   	`} else {`
   		`this.headers.putAll(headers);`
   	`}`
   	`return this;`
   `}`

   `public HttpKit2 upload(String key, File file) {`
   	`if (uploads == null) {`
   		`uploads = new HashMap<>();`
   	`}`
   	`uploads.put(key, file);`
   	`return this;`
   `}`

   `public HttpKit2 body(Object o) {`
   	`this.body = o;`
   	`return this;`
   `}`

   `public HttpKit2 upload(Map<String, File> files) {`
   	`if (files == null || files.isEmpty()) {`
   		`return this;`
   	`}`
   	`if (this.uploads == null || this.uploads.isEmpty()) {`
   		`this.uploads = files;`
   	`} else {`
   		`this.uploads.putAll(files);`
   	`}`
   	`return this;`
   `}`

   `public HttpKit2 param(String key, Object value) {`
   	`if (params == null) {`
   		`params = new HashMap<>();`
   	`}`
   	`params.put(key, value);`
   	`return this;`
   `}`

   `public HttpKit2 param(Map<String, Object> params) {`
   	`if (params == null || params.isEmpty()) {`
   		`return this;`
   	`}`
   	`if (this.params == null) {`
   		`this.params = new HashMap<>();`
   	`}`
   	`this.params.putAll(params);`
   	`return this;`
   `}`

   `public HttpKit2 getUrl(String url) {`
   	`this.url = url;`
   	`this.method = null;`
   	`return this;`
   `}`

   `public HttpKit2 postUrl(String url) {`
   	`this.url = url;`
   	`this.method = "POST";`
   	`return this;`
   `}`

   `/**`

    * `@author guweichao`

    * <p>

    * `实际执行http请求的方法,需要先执行getUrl 或 postUrl`

    * `</p>`

    * `重复执行,需要重新执行 getUrl(postUrl) params headers uploads`

    * `@created_at 2020-9-3 10:38:47`

    * `@return true | false`
      `*/`
      `public boolean doHttp() {`
      `HttpURLConnection conn = null;`
      `try {`
      	`this.resultString = null;`
      	`this.resultList = null;`
      	`this.resultStream = null;`
      	`this.exception = null;`
      	`if (url == null) {`
      		`this.resultString = "url is null";`
      		`return false;`
      	`}`
      	`URL connurl = new URL(urlWithParams(url, params));`
      	`url = null;`
      	`if (params != null && !params.isEmpty()) {`
      		`params.clear();`
      	`}`
      	`conn = (HttpURLConnection) connurl.openConnection();`
      	`conn.setConnectTimeout(timeout);`
      	`conn.setReadTimeout(timeout);`
      	`conn.setUseCaches(false);`
      	`conn.setRequestProperty("Charset", "UTF-8");`
      	`conn.setRequestProperty("Connection", "Keep-Alive");`
      	`conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");`
      	`final HttpURLConnection conn1 = conn;`
      	`if (requestProperties != null && !requestProperties.isEmpty()) {`
      		`requestProperties.forEach((k, v) -> conn1.setRequestProperty(k, v));`
      	`}`
      	`if (method != null) {`
      		`conn.setRequestMethod(method);`
      		`conn.setDoInput(true);`
      		`conn.setDoOutput(true);`
      	`}`
      	`if (headers != null && !headers.isEmpty()) {`
      		`headers.forEach((k, v) -> conn1.setRequestProperty(k, v));`
      		`headers.clear();`
      	`}`
      	`if (body != null) {`
      		`conn.getOutputStream().write(JsonKit.toJson(body).getBytes());`
      		`body = null;`
      	`}`

      	if (uploads != null && !uploads.isEmpty()) {
      		conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
      		try (DataOutputStream ds = new DataOutputStream(conn.getOutputStream());) {
      			for (Map.Entry<String, File> entry : uploads.entrySet()) {
      				ds.writeBytes(prefix + boundary + end);
      				String name = entry.getKey();
      				File file = entry.getValue();
      				String filename = file.getName();
      				ds.writeBytes("Content-Disposition: form-data; " + "name=\"" + name + "\";filename=\""
      						+ filename + "\"");
      				ds.writeBytes(end);
      				ds.writeBytes(end);
      				try (FileInputStream fStream = new FileInputStream(file);) {
      					int bufferSize = 1024;
      					byte[] buffer = new byte[bufferSize];
      					int length = -1;
      					while ((length = fStream.read(buffer)) != -1) {
      						ds.write(buffer, 0, length);
      					}
      					ds.writeBytes(end);
      				} catch (Exception e) {
      					this.exception = e;
      					this.resultString = StringKit.parseException(e);
      					return false;
      				}
      	
      			}
      			ds.writeBytes(prefix + boundary + prefix + end);
      			ds.flush();
      		} catch (Exception e) {
      			this.exception = e;
      			this.resultString = StringKit.parseException(e);
      		}
      		uploads.clear();
      	}
      	conn.connect();
      	boolean rc = conn.getResponseCode() == 200;
      	InputStream in = rc ? conn.getInputStream() : conn.getErrorStream();
      	if (in != null) {
      		baos = new ByteArrayOutputStream();
      		byte[] buffer = new byte[1024];
      		int len;
      		while ((len = in.read(buffer)) > -1) {
      			baos.write(buffer, 0, len);
      		}
      		baos.flush();
      		in.close();
      	}
      	return rc;

      `} catch (Exception e) {`
      	`this.exception = e;`
      	`this.resultString = StringKit.parseException(e);`
      `} finally {`
      	`if (conn != null) {`
      		`try {`
      			`conn.disconnect();`
      		`} catch (Exception e2) {`
      			`e2.printStackTrace();`
      		`}`
      	`}`
      `}`
      `return false;`
      `}`

   `private static final String defaultCharset = "utf-8";`

   `private static String urlWithParams(String url, Map<?, ?> params) {`
   	`if (params != null && params.size() > 0) {`
   		`Joiner urlparams = new Joiner("&");`
   		`params.forEach((k, v) -> {`
   			`urlparams.add(encode(k) + "=" + encode(v));`
   		`});`
   		`return url + "?" + urlparams.toString();`
   	`}`
   	`return url;`
   `}`

   `public static String encode(Object str) {`
   	`return encode(StringKit.of(str));`
   `}`

   `public static String encode(String str) {`
   	`try {`
   		`return URLEncoder.encode(str, defaultCharset).replace("+", "%20");`
   	`} catch (Exception e) {`
   		`throw new RuntimeException(e);`
   	`}`
   `}`

`}`
posted @ 2020-12-11 20:23  来一杯coffee  阅读(86)  评论(0)    收藏  举报