RestTemplate
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSONObject;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
@Setter
@Slf4j
public class RestTemplateUtils {
private String charset;
private String url;
private MultiValueMap<String,String> headers = new LinkedMultiValueMap<String,String>();
private Object postParams = new Object();
private RestTemplate getInstance() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(60000);
requestFactory.setReadTimeout(60000);
RestTemplate restTemplate = new RestTemplate(requestFactory);
List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
for (HttpMessageConverter<?> httpMessageConverter : list) {
if(httpMessageConverter instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName(charset));
}
}
return restTemplate;
}
public JSONObject getPOSTResponseBody() {
RestTemplate restTemplate = getInstance();
HttpEntity<Object> httpEntity=new HttpEntity<Object>(postParams,headers);
log.info("url: " + url);
log.info("请求头:" + httpEntity.getHeaders());
log.info("请求体:" + httpEntity.getBody());
ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(url, HttpMethod.POST,httpEntity,JSONObject.class);
JSONObject responeseBody = responseEntity.getBody();
log.info("响应: " + responeseBody.toString());
return responeseBody;
}
public InputStream getPOSTResponseFile() throws IOException {
RestTemplate restTemplate = getInstance();
HttpEntity<Object> httpEntity=new HttpEntity<Object>(postParams,headers);
log.info("url: " + url);
log.info("请求头:" + httpEntity.getHeaders());
log.info("请求体:" + httpEntity.getBody());
ResponseEntity<Resource> responseEntity = restTemplate.exchange(url, HttpMethod.POST,httpEntity,Resource.class);
InputStream responeseBody = responseEntity.getBody().getInputStream();
log.info("响应: " + responeseBody.toString());
return responeseBody;
}
public String getGetResponseBode() {
RestTemplate restTemplate = getInstance();
HttpEntity<MultiValueMap<String,Object>> httpEntity=new HttpEntity<MultiValueMap<String,Object>>(new LinkedMultiValueMap<String,Object>(), headers);
log.info("url: " + url);
log.info("请求头:" + httpEntity.getHeaders());
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET,httpEntity,String.class);
String responeseBody = responseEntity.getBody();
log.info("响应: " + responeseBody.toString());
return responeseBody;
}
}
代理
import java.io.IOException;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URL;
import org.apache.commons.codec.binary.Base64;
/**
* 代理访问(内网通过代理服务器访问外网)
*/
public class ProxyHttpUtil {
/**
* @param url http访问的url地址
* @param proxyHost 代理访问的域名或ip(源服务器无法访问或不方便访问)
* @param proxyPort 代理服务器端口
* @param userName 代理服务 认证用户名
* @param password 认证密码
* @return
* @throws IOException
*/
public HttpURLConnection getHttpConnect(URL url, String proxyHost, String proxyPort, String userName, String password) throws IOException {
System.setProperty("http.proxyHost", proxyHost);
System.setProperty("http.proxyPort", proxyPort);
Authenticator.setDefault(new BasicAuthenticator(userName, password));
return (HttpURLConnection)url.openConnection();
}
/**
* @param url http访问url地址
* @param proxyHost 代理服务器ip (最后用ip 也可使用域名)
* @param proxyPort 代理端口
* @param userName 认证用户名
* @param password 认证密码
* @return
* @throws IOException
*/
public HttpURLConnection getHttpConnect(URL url, String proxyHost, int proxyPort, String userName, String password) throws IOException {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
HttpURLConnection con = (HttpURLConnection)url.openConnection(proxy);
String headerkey = "Proxy-Authorization";
String up = userName+":"+ password;
String headerValue = "Basic "+Base64.encodeBase64String(up.getBytes("UTF-8"));
con.setRequestProperty(headerkey, headerValue);
return con;
}
}
class BasicAuthenticator extends Authenticator {
String userName;
String password;
public BasicAuthenticator(String userName, String password) {
this.userName = userName;
this.password = password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password.toCharArray());
}
}
HttpUrlConnection
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
@Getter
@Setter
@Slf4j
public class HttpUrlConnectUtil {
public static String CharSet = "UTF-8";
private final String GET = "GET";
private final String POST = "POST";
private String uri;
private Map<String,String> headers = new HashMap<String,String>();
// private
private InputStream reqBodyIn;
private HttpURLConnection connction;
private void connect(String method) throws IOException {
log.info("请求路径:{}", uri);
log.info("请求方式:{}", method);
URL url = null;
url = new URL(this.uri);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod(method);
con.setDoOutput(true);
con.setUseCaches(false);
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
for(Map.Entry<String, String> entry : this.headers.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
log.info("设置请求头:{} : {}", key, value);
con.setRequestProperty(key, value);
}
con.connect();
if(this.POST.equals(method)) {
log.info("POST请求,设置请求体");
OutputStream out = con.getOutputStream();
try {
byte [] car = new byte [1024];
int len = 0;
while((len = this.reqBodyIn.read(car)) != -1) {
out.write(car, 0, len);
}
out.flush();
log.info("请求体设置成功");
}finally {
if(out != null)out.close();
}
}
log.info("开始响应处理");
int code = con.getResponseCode();
log.info("状态码:{}", code);
if(code == 200) {
log.info("请求成功");
}else {
log.info("请求异常");
}
this.connction = con;
}
public void getGetConnction() throws IOException {
connect(this.GET);
}
public void getPOSTConnection(InputStream dataIn) throws IOException {
this.reqBodyIn = dataIn;
connect(this.POST);
}
public InputStream getResponIn() throws IOException {
log.info("获取响应流");
InputStream in = this.connction.getInputStream();
return in;
}
public String getResponseStr() throws IOException {
StringBuffer respString=new StringBuffer();
InputStream in = this.getResponIn();
try {
log.info("读取流 生产字符串");
BufferedReader br = new BufferedReader(new InputStreamReader(in, CharSet));
String car = null;
while((car=br.readLine())!=null) {
respString.append(car);
}
String respStr = respString.toString();
log.info("返回字符串");
return respStr;
}finally {
if(in != null) in.close();
}
}
}
socket
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SocketUtil {
private boolean isHttps;
private Socket socket;
private String host;
private OutputStream os;
private BufferedReader is;
public static void main(String [] args) {
SocketUtil socketUtil = new SocketUtil();
socketUtil.setHttps(false);
Map<String,String> headers = new HashMap<String,String>();
headers.put("Content-Type", "application/json");
JSONObject json = new JSONObject();
String dataStr = json.toJSONString();
try {
socketUtil.connect("域名", 8080);
socketUtil.setRequestData("域名后的具体url地址如:/Get/map", headers, dataStr);
System.out.println(socketUtil.getResponseStr());
socketUtil.closeHttp();
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean connect(String host, int port) {
this.host = host;
if(isHttps) {
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext ctx;
try {
// socket = (SSLSocket)((SSLSocketFactory)SSLSocketFactory.getDefault()).createSocket( );
ctx = SSLContext.getInstance("TLSv1.2");
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory factory = ctx.getSocketFactory();
socket = factory.createSocket(host, port);
log.info("socket连接建立成功");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
try {
socket = new Socket();
SocketAddress dest = new InetSocketAddress(host, port);
socket.connect(dest);
log.info("socket连接建立成功");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public void setRequestData(String url, Map<String,String> headers,String data) throws UnsupportedEncodingException, IOException {
os = socket.getOutputStream();
is = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
StringBuffer headerBuf = new StringBuffer();
headerBuf.append("POST " + url + " HTTP/1.1\r\n");
headerBuf.append("Host: " + host + "\r\n");
for(String key: headers.keySet()) {
headerBuf.append(key +": " + headers.get(key) + "\r\n");
}
headerBuf.append("\r\n");
log.info(headerBuf.toString());
os.write(headerBuf.toString().getBytes("UTF-8"));
log.info("请求头写入完毕");
int length = data.length();
byte [] bytes= data.getBytes("UTF-8");
log.info("数据长度=" + length);
log.info("开始写入数据");
os.write(bytes);
os.flush();
log.info("请求参数写入完毕");
System.out.println(headerBuf.toString());
System.out.println(data.toString());
}
public String getResponseStr() throws IOException {
String line = null;
StringBuffer result = new StringBuffer();
boolean respOk = false;
while((line = is.readLine())!= null){
log.info("响应:" + line);
if(respOk) {
result.append(line);
}
if("".equals(line.trim())) {
respOk = true;
}
}
log.info("关闭socket,返回响应正文");
return result.toString();
}
public void closeHttp() throws IOException {
if(os != null) os.close();
}
public boolean isHttps() {
return isHttps;
}
public void setHttps(boolean isHttps) {
this.isHttps = isHttps;
}
}