ConnectionAction.java 17.1 KB
Newer Older
R
test  
roo00 已提交
1 2
package com.x.base.core.project.connection;

Z
zhourui 已提交
3
import java.io.ByteArrayOutputStream;
R
test  
roo00 已提交
4 5 6 7 8 9
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
Z
zhourui 已提交
10
import java.util.Collection;
R
test  
roo00 已提交
11 12 13
import java.util.List;
import java.util.Map;
import java.util.Objects;
Z
zhourui 已提交
14
import java.util.TreeMap;
R
test  
roo00 已提交
15 16 17 18 19 20

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.x.base.core.project.bean.NameValuePair;
import com.x.base.core.project.gson.XGsonBuilder;
Z
zhourui 已提交
21
import com.x.base.core.project.http.ActionResult.Type;
R
test  
roo00 已提交
22 23
import com.x.base.core.project.tools.DefaultCharset;
import com.x.base.core.project.tools.ListTools;
Z
zhourui 已提交
24
import com.x.base.core.project.tools.StringTools;
Z
zhourui 已提交
25 26 27

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
NoSubject's avatar
NoSubject 已提交
28
import org.apache.http.HttpEntity;
O
o2sword 已提交
29 30
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
NoSubject's avatar
NoSubject 已提交
31 32
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
R
test  
roo00 已提交
33 34 35

public class ConnectionAction {

Z
zhourui 已提交
36 37 38 39 40 41 42 43 44
	private ConnectionAction() {
	}

	public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
	public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS_VALUE = "true";
	public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
	public static final String ACCESS_CONTROL_ALLOW_HEADERS_VALUE = "x-requested-with, x-request, x-token,Content-Type, x-cipher, x-client";
	public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
	public static final String ACCESS_CONTROL_ALLOW_METHODS_VALUE = "GET, POST, OPTIONS, PUT, DELETE, HEAD, TRACE";
R
roo00 已提交
45

Z
zhourui 已提交
46 47 48 49 50
	public static final String CACHE_CONTROL = "Cache-Control";
	public static final String CACHE_CONTROL_VALUE = "no-cache, no-transform";
	public static final String CONTENT_TYPE = "Content-Type";
	public static final String CONTENT_TYPE_VALUE = "application/json;charset=UTF-8";
	public static final String CONTENT_LENGTH = "Content-Length";
R
roo00 已提交
51 52 53 54 55

	public static final String METHOD_PUT = "PUT";
	public static final String METHOD_POST = "POST";
	public static final String METHOD_GET = "GET";
	public static final String METHOD_DELETE = "DELETE";
R
test  
roo00 已提交
56 57 58

	private static Gson gson = XGsonBuilder.instance();

Z
zhourui 已提交
59
	private static ActionResponse getDelete(String address, String method, List<NameValuePair> heads) throws Exception {
R
test  
roo00 已提交
60 61 62 63 64 65
		ActionResponse response = new ActionResponse();
		HttpURLConnection connection = null;
		try {
			URL url = new URL(address);
			connection = (HttpURLConnection) url.openConnection();
		} catch (Exception e) {
Z
zhourui 已提交
66 67 68
			response.setType(Type.connectFatal);
			response.setMessage(String.format("%s create connection error, address: %s, because: %s.", method, address,
					e.getMessage()));
R
test  
roo00 已提交
69 70 71
			return response;
		}
		addHeads(connection, heads);
Z
zhourui 已提交
72
		connection.setRequestMethod(method);
R
test  
roo00 已提交
73 74 75 76 77 78
		connection.setUseCaches(false);
		connection.setDoOutput(false);
		connection.setDoInput(true);
		try {
			connection.connect();
		} catch (Exception e) {
Z
zhourui 已提交
79 80 81
			response.setType(Type.connectFatal);
			response.setMessage(String.format("%s connect connection error, address: %s, because: %s.", method, address,
					e.getMessage()));
R
test  
roo00 已提交
82 83 84 85 86
			return response;
		}
		return read(response, connection);
	}

Z
zhourui 已提交
87 88 89 90
	public static ActionResponse get(String address, List<NameValuePair> heads) throws Exception {
		return getDelete(address, METHOD_GET, heads);
	}

R
test  
roo00 已提交
91
	public static ActionResponse delete(String address, List<NameValuePair> heads) throws Exception {
Z
zhourui 已提交
92 93 94 95
		return getDelete(address, METHOD_DELETE, heads);
	}

	private static byte[] getDeleteBinary(String address, String method, List<NameValuePair> heads) throws Exception {
R
test  
roo00 已提交
96 97 98 99 100
		HttpURLConnection connection = null;
		try {
			URL url = new URL(address);
			connection = (HttpURLConnection) url.openConnection();
		} catch (Exception e) {
Z
zhourui 已提交
101
			throw new ExceptionGetBinary(e, connection);
R
test  
roo00 已提交
102 103
		}
		addHeads(connection, heads);
Z
zhourui 已提交
104
		connection.setRequestMethod(method);
R
test  
roo00 已提交
105 106 107 108 109 110
		connection.setUseCaches(false);
		connection.setDoOutput(false);
		connection.setDoInput(true);
		try {
			connection.connect();
		} catch (Exception e) {
Z
zhourui 已提交
111
			throw new ExceptionGetBinary(e, connection);
R
test  
roo00 已提交
112
		}
Z
zhourui 已提交
113
		return readBinary(connection);
R
test  
roo00 已提交
114 115
	}

Z
zhourui 已提交
116 117 118 119 120 121 122 123 124 125
	public static byte[] getBinary(String address, List<NameValuePair> heads) throws Exception {
		return getDeleteBinary(address, METHOD_GET, heads);
	}

	public static byte[] deleteBinary(String address, List<NameValuePair> heads) throws Exception {
		return getDeleteBinary(address, METHOD_DELETE, heads);
	}

	public static ActionResponse postPut(String address, String method, List<NameValuePair> heads, Object body)
			throws Exception {
R
test  
roo00 已提交
126 127 128 129 130 131
		ActionResponse response = new ActionResponse();
		HttpURLConnection connection = null;
		try {
			URL url = new URL(address);
			connection = (HttpURLConnection) url.openConnection();
		} catch (Exception e) {
Z
zhourui 已提交
132 133 134
			response.setType(Type.connectFatal);
			response.setMessage(String.format("%s create connection error, address: %s, because: %s.", method, address,
					e.getMessage()));
R
test  
roo00 已提交
135 136 137
			return response;
		}
		addHeads(connection, heads);
Z
zhourui 已提交
138
		connection.setRequestMethod(method);
R
test  
roo00 已提交
139 140 141 142 143 144
		connection.setUseCaches(false);
		connection.setDoOutput(true);
		connection.setDoInput(true);
		try {
			connection.connect();
		} catch (Exception e) {
Z
zhourui 已提交
145 146 147
			response.setType(Type.connectFatal);
			response.setMessage(
					String.format("%s connect error, address: %s, because: %s.", method, address, e.getMessage()));
R
test  
roo00 已提交
148 149 150 151 152 153 154 155 156 157 158
			return response;
		}
		try (OutputStream output = connection.getOutputStream()) {
			if (null != body) {
				if (body instanceof CharSequence) {
					IOUtils.write(Objects.toString(body), output, StandardCharsets.UTF_8);
				} else {
					IOUtils.write(gson.toJson(body), output, StandardCharsets.UTF_8);
				}
			}
		} catch (Exception e) {
Z
zhourui 已提交
159 160 161
			response.setType(Type.connectFatal);
			response.setMessage(
					String.format("%s ouput error, address: %s, because: %s.", method, address, e.getMessage()));
R
test  
roo00 已提交
162 163 164 165 166
			return response;
		}
		return read(response, connection);
	}

Z
zhourui 已提交
167 168 169 170
	public static ActionResponse post(String address, List<NameValuePair> heads, Object body) throws Exception {
		return postPut(address, METHOD_POST, heads, body);
	}

R
test  
roo00 已提交
171
	public static ActionResponse put(String address, List<NameValuePair> heads, Object body) throws Exception {
Z
zhourui 已提交
172 173 174 175 176
		return postPut(address, METHOD_PUT, heads, body);
	}

	private static byte[] postPutBinary(String address, String method, List<NameValuePair> heads, Object body)
			throws Exception {
R
test  
roo00 已提交
177 178 179 180 181
		HttpURLConnection connection = null;
		try {
			URL url = new URL(address);
			connection = (HttpURLConnection) url.openConnection();
		} catch (Exception e) {
Z
zhourui 已提交
182
			throw new ExceptionBinary(e, connection);
R
test  
roo00 已提交
183 184
		}
		addHeads(connection, heads);
Z
zhourui 已提交
185
		connection.setRequestMethod(method);
R
test  
roo00 已提交
186 187 188 189 190 191
		connection.setUseCaches(false);
		connection.setDoOutput(true);
		connection.setDoInput(true);
		try {
			connection.connect();
		} catch (Exception e) {
Z
zhourui 已提交
192
			throw new ExceptionBinary(e, connection);
R
test  
roo00 已提交
193 194 195 196 197 198 199 200 201 202
		}
		try (OutputStream output = connection.getOutputStream()) {
			if (null != body) {
				if (body instanceof CharSequence) {
					IOUtils.write(Objects.toString(body), output, StandardCharsets.UTF_8);
				} else {
					IOUtils.write(gson.toJson(body), output, StandardCharsets.UTF_8);
				}
			}
		} catch (Exception e) {
Z
zhourui 已提交
203
			throw new ExceptionBinary(e, connection);
R
test  
roo00 已提交
204
		}
Z
zhourui 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
		return readBinary(connection);
	}

	public static byte[] postBinary(String address, List<NameValuePair> heads, Object body) throws Exception {
		return postPutBinary(address, METHOD_POST, heads, body);
	}

	public static byte[] putBinary(String address, List<NameValuePair> heads, Object body) throws Exception {
		return postPutBinary(address, METHOD_PUT, heads, body);
	}

	private static byte[] postPutMultiPartBinary(String address, String method, List<NameValuePair> heads,
			Collection<FormField> formFields, Collection<FilePart> fileParts) throws Exception {
		HttpURLConnection connection = null;
		String boundary = StringTools.TWO_HYPHENS + StringTools.TWO_HYPHENS + System.currentTimeMillis();
		try {
			URL url = new URL(address);
			connection = (HttpURLConnection) url.openConnection();
		} catch (Exception e) {
			throw new ExceptionMultiPartBinary(e, connection);
		}
		byte[] bytes = null;
		try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
			if (null != fileParts) {
				for (FilePart filePart : fileParts) {
					writeFilePart(byteArrayOutputStream, filePart, boundary);
				}
			}
			if (null != formFields) {
				for (FormField formField : formFields) {
					writeFormField(byteArrayOutputStream, formField, boundary);
				}
			}
			IOUtils.write(StringTools.TWO_HYPHENS + boundary + StringTools.TWO_HYPHENS, byteArrayOutputStream,
					DefaultCharset.charset_utf_8);
			bytes = byteArrayOutputStream.toByteArray();
		} catch (Exception e) {
			throw new ExceptionMultiPartBinary(e, connection);
		}
		addHeadsMultiPart(connection, heads, boundary);
		connection.setRequestProperty(CONTENT_LENGTH, bytes.length + "");
		connection.setRequestMethod(method);
		connection.setUseCaches(false);
		connection.setDoOutput(true);
		connection.setDoInput(true);
		try {
			connection.connect();
		} catch (Exception e) {
			throw new ExceptionMultiPartBinary(e, connection);
		}
		try (OutputStream output = connection.getOutputStream()) {
			IOUtils.write(bytes, output);
		} catch (Exception e) {
			throw new ExceptionMultiPartBinary(e, connection);
		}
		return readBinary(connection);
	}

	public static byte[] postMultiPartBinary(String address, List<NameValuePair> heads,
			Collection<FormField> formFields, Collection<FilePart> fileParts) throws Exception {
		return postPutMultiPartBinary(address, METHOD_POST, heads, formFields, fileParts);
	}

	public static byte[] putMultiPartBinary(String address, List<NameValuePair> heads, Collection<FormField> formFields,
			Collection<FilePart> fileParts) throws Exception {
		return postPutMultiPartBinary(address, METHOD_PUT, heads, formFields, fileParts);
	}

	private static void writeFormField(OutputStream output, FormField formField, String boundary) throws IOException {
		IOUtils.write(StringTools.TWO_HYPHENS + boundary, output, StandardCharsets.UTF_8);
		IOUtils.write(StringTools.CRLF, output, StandardCharsets.UTF_8);
		IOUtils.write("Content-Disposition: form-data; name=\"" + formField.getName() + "\"", output,
				StandardCharsets.UTF_8);
		IOUtils.write(StringTools.CRLF, output, StandardCharsets.UTF_8);
		IOUtils.write("Content-Length: " + formField.getValue().getBytes(StandardCharsets.UTF_8).length, output,
				StandardCharsets.UTF_8);
		IOUtils.write(StringTools.CRLF, output, StandardCharsets.UTF_8);
		IOUtils.write("Content-Type: text/plain; charset=" + StandardCharsets.UTF_8.name(), output,
				StandardCharsets.UTF_8);
		IOUtils.write(StringTools.CRLF, output, StandardCharsets.UTF_8);
		IOUtils.write(StringTools.CRLF, output, StandardCharsets.UTF_8);
		IOUtils.write(formField.getValue().getBytes(StandardCharsets.UTF_8), output);
		IOUtils.write(StringTools.CRLF, output, StandardCharsets.UTF_8);
	}

	public static void writeFilePart(OutputStream output, FilePart filePart, String boundary) throws IOException {
		IOUtils.write(StringTools.TWO_HYPHENS + boundary, output, StandardCharsets.UTF_8);
		IOUtils.write(StringTools.CRLF, output, StandardCharsets.UTF_8);
		IOUtils.write(
				"Content-Disposition: form-data; name=\"" + filePart.getName().getBytes(StandardCharsets.UTF_8)
						+ "\"; filename=\"" + filePart.getFileName().getBytes(StandardCharsets.UTF_8) + "\"",
				output, StandardCharsets.UTF_8);
		IOUtils.write(StringTools.CRLF, output, StandardCharsets.UTF_8);
		IOUtils.write("Content-Length: " + filePart.getBytes().length, output, StandardCharsets.UTF_8);
		IOUtils.write(StringTools.CRLF, output, StandardCharsets.UTF_8);
		IOUtils.write("Content-Type: " + filePart.getContentType(), output, StandardCharsets.UTF_8);
		IOUtils.write(StringTools.CRLF, output, StandardCharsets.UTF_8);
		IOUtils.write(String.format("Content-Length: %d", filePart.getBytes().length), output, StandardCharsets.UTF_8);
		IOUtils.write(StringTools.CRLF, output, StandardCharsets.UTF_8);
		IOUtils.write(StringTools.CRLF, output, StandardCharsets.UTF_8);
		IOUtils.write(filePart.getBytes(), output);
		IOUtils.write(StringTools.CRLF, output, StandardCharsets.UTF_8);
R
test  
roo00 已提交
307 308
	}

O
o2sword 已提交
309
	public static byte[] getFile(String address, List<NameValuePair> heads) throws Exception {
Z
zhourui 已提交
310
		try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
O
o2sword 已提交
311 312 313 314 315 316 317 318 319 320 321 322 323 324
			HttpGet httpget = new HttpGet(address);
			if (ListTools.isNotEmpty(heads)) {
				String name;
				String value;
				for (NameValuePair o : heads) {
					name = Objects.toString(o.getName(), "");
					value = Objects.toString(o.getValue(), "");
					if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(value)) {
						httpget.addHeader(name, value);
					}
				}
			}
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
Z
zhourui 已提交
325
			if (entity != null) {
O
o2sword 已提交
326
				InputStream in = entity.getContent();
Z
zhourui 已提交
327
				if (in != null) {
O
o2sword 已提交
328 329 330 331 332 333 334
					return IOUtils.toByteArray(in);
				}
			}
		}
		return null;
	}

R
test  
roo00 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347
	private static String extractErrorMessageIfExist(String str) {
		if (StringUtils.isBlank(str)) {
			return "";
		}
		try {
			JsonElement jsonElement = gson.fromJson(str, JsonElement.class);
			if (jsonElement.isJsonObject()) {
				ActionResponse ar = gson.fromJson(jsonElement, ActionResponse.class);
				if (StringUtils.isNotEmpty(ar.getMessage())) {
					return ar.getMessage();
				}
			}
		} catch (JsonParseException e) {
Z
zhourui 已提交
348
			// nothing
R
test  
roo00 已提交
349 350 351 352 353 354 355 356 357 358
		}
		return str;
	}

	private static ActionResponse read(ActionResponse response, HttpURLConnection connection) throws IOException {
		int code = connection.getResponseCode();
		if (code >= 500) {
			try (InputStream input = connection.getErrorStream()) {
				byte[] buffer = IOUtils.toByteArray(input);
				response.setMessage(extractErrorMessageIfExist(new String(buffer, DefaultCharset.name)));
Z
zhourui 已提交
359
				response.setType(Type.error);
R
test  
roo00 已提交
360 361
			}
		} else if (code >= 400) {
Z
zhourui 已提交
362 363 364
			response.setMessage(String.format("url invalid error, address: %s, method: %s, code: %d.",
					Objects.toString(connection.getURL()), connection.getRequestMethod(), code));
			response.setType(Type.error);
R
test  
roo00 已提交
365 366 367 368
		} else if (code == 200) {
			try (InputStream input = connection.getInputStream()) {
				byte[] buffer = IOUtils.toByteArray(input);
				String value = new String(buffer, DefaultCharset.name);
Z
zhourui 已提交
369
				response = gson.fromJson(value, ActionResponse.class);
R
test  
roo00 已提交
370
			} catch (Exception e) {
Z
zhourui 已提交
371 372 373 374
				response.setType(Type.connectFatal);
				response.setMessage(String.format(
						"convert input to json error, address: %s, method: %s, code: %d, because: %s.",
						Objects.toString(connection.getURL()), connection.getRequestMethod(), code, e.getMessage()));
R
test  
roo00 已提交
375 376 377 378 379 380
			}
		}
		connection.disconnect();
		return response;
	}

Z
zhourui 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
	private static byte[] readBinary(HttpURLConnection connection) throws Exception {
		int code = connection.getResponseCode();
		byte[] bytes = null;
		if (code >= 500) {
			try (InputStream input = connection.getErrorStream()) {
				byte[] buffer = IOUtils.toByteArray(input);
				throw new ExceptionReadBinary(connection.getURL(), connection.getRequestMethod(), code, buffer);
			}
		} else if (code >= 400) {
			throw new ExceptionReadBinary(connection.getURL(), connection.getRequestMethod(), code);
		} else if (code == 200) {
			try (InputStream input = connection.getInputStream()) {
				bytes = IOUtils.toByteArray(input);
			} catch (Exception e) {
				throw new ExceptionReadBinary(e, connection, code);
			}
		}
		connection.disconnect();
		return bytes;
	}

R
test  
roo00 已提交
402
	private static void addHeads(HttpURLConnection connection, List<NameValuePair> heads) {
Z
zhourui 已提交
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
		Map<String, String> map = new TreeMap<>();
		map.put(ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_CREDENTIALS_VALUE);
		map.put(ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_HEADERS_VALUE);
		map.put(ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_METHODS_VALUE);
		map.put(CACHE_CONTROL, CACHE_CONTROL_VALUE);
		map.put(CONTENT_TYPE, CONTENT_TYPE_VALUE);
		if (ListTools.isNotEmpty(heads)) {
			String value;
			for (NameValuePair o : heads) {
				value = Objects.toString(o.getValue(), "");
				if (StringUtils.isNotEmpty(o.getName()) && StringUtils.isNotEmpty(value)) {
					map.put(o.getName(), value);
				}
			}
		}
		map.entrySet().forEach((o -> connection.addRequestProperty(o.getKey(), o.getValue())));
	}

	private static void addHeadsMultiPart(HttpURLConnection connection, List<NameValuePair> heads, String boundary) {
		Map<String, String> map = new TreeMap<>();
		map.put(ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_CREDENTIALS_VALUE);
		map.put(ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_HEADERS_VALUE);
		map.put(ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_METHODS_VALUE);
		map.put(CACHE_CONTROL, CACHE_CONTROL_VALUE);
		connection.setRequestProperty(CONTENT_TYPE, String.format("multipart/form-data; boundary=%s", boundary));
R
test  
roo00 已提交
428 429 430 431
		if (ListTools.isNotEmpty(heads)) {
			String value;
			for (NameValuePair o : heads) {
				value = Objects.toString(o.getValue(), "");
Z
zhourui 已提交
432 433
				if (StringUtils.isNotEmpty(o.getName()) && StringUtils.isNotEmpty(value)) {
					map.put(o.getName(), value);
R
test  
roo00 已提交
434 435 436
				}
			}
		}
Z
zhourui 已提交
437
		map.entrySet().forEach((o -> connection.addRequestProperty(o.getKey(), o.getValue())));
R
test  
roo00 已提交
438 439 440
	}

}