Socket的特点:属于传输层,是对Tcp/IP协议的实现
1.开启端口,该通信为长连接通信,很容易被防火墙回收,可以通过心跳机制来实现,但是开发难度会比较大。
2.传输的数据是字符串,可读性不强
3.socket端口不便于推广
http://45.113.192.102:2345 www.baidu.com
4.性能相较于其他通信协议是最优秀的
Http协议访问:属于应用层的协议,对socket进行了封装
1.跨平台
2.传数据不够友好
http://localhost:8080?username=jack&age=18
/**
* rest 缓存考虑若要利用无状态操作的特性,
*
* 有限的带宽和资源情况下使用
*
* 返回的结构可以采用(由开发者定义的)任何格式
*
* @author xxx
*
*/
public class HttpClient {
private static final Logger LOG = LoggerFactory.getLogger(HttpClient.class);
public static String get(List<String> params) {
String url = "http://localhost:8080/Base/testGet?username=" + params.get(0);
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建httpGet对象
HttpGet httpGet = new HttpGet(url);
// 响应对象
CloseableHttpResponse response = null;
try {
// 执行请求
response = httpClient.execute(httpGet);
// 获取响应实体
HttpEntity httpEntity = response.getEntity();
// 获取响应内容
if (httpEntity != null) {
return EntityUtils.toString(httpEntity);
}
} catch (ClientProtocolException e) {
LOG.error("ClientProtocolException", e);
} catch (IOException e) {
LOG.error("IOException", e);
} finally {
try {
// 释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
LOG.error("IOException", e);
}
}
return null;
}
public static String post(List<String> params) {
String url = "http://localhost:8080/Base/testPost";
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建httpGet对象
HttpPost httpPost = new HttpPost(url);
// 设置post请求参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("username", params.get(0)));
list.add(new BasicNameValuePair("password", params.get(1)));
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list);
httpPost.setEntity(entity);
} catch (UnsupportedEncodingException e) {
LOG.error("UnsupportedEncodingException", e);
}
// 响应对象
CloseableHttpResponse response = null;
try {
// 执行请求
response = httpClient.execute(httpPost);
// 获取响应实体
HttpEntity httpEntity = response.getEntity();
// 获取响应内容
if (httpEntity != null) {
return EntityUtils.toString(httpEntity);
}
} catch (ClientProtocolException e) {
LOG.error("ClientProtocolException", e);
} catch (IOException e) {
LOG.error("IOException", e);
} finally {
try {
// 释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
LOG.error("IOException", e);
}
}
return null;
}
}