[toc]
HttpURLConnection
在java.net包中,已经提供访问HTTP协议的基本功能类:HttpURLConnection,可以向其他系统发送GET,POST访问请求
private void httpURLGETCase() {
String methodUrl = "http://110.32.44.11:8086/sp-test/usertest/1.0/query";
HttpURLConnection connection = null;
BufferedReader reader = null;
String line = null;
try {
URL url = new URL(methodUrl + "?mobile=15334567890&name=zhansan");
connection = (HttpURLConnection) url.openConnection();// 根据URL生成HttpURLConnection
connection.setRequestMethod("GET");// 默认GET请求
connection.connect();// 建立TCP连接
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 发送http请求
StringBuilder result = new StringBuilder();
// 循环读取流
while ((line = reader.readLine()) != null) {
result.append(line).append(System.getProperty("line.separator"));// "\n"
}
System.out.println(result.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
connection.disconnect();
}
}
HttpClient
Spring RestTemplate
- delete() 在特定的URL上对资源执行HTTP DELETE操作
- exchange() 在URL上执行特定的HTTP方法,返回包含对象的ResponseEntity,这个对象是从响应体中映射得到的
- execute() 在URL上执行特定的HTTP方法,返回一个从响应体映射得到的对象
- getForEntity() 发送一个HTTP GET请求,返回的ResponseEntity包含了响应体所映射成的对象
- getForObject() 发送一个HTTP GET请求,返回的请求体将映射为一个对象
- postForEntity() POST 数据到一个URL,返回包含一个对象的ResponseEntity,这个对象是从响应体中映射得到的
- postForObject() POST 数据到一个URL,返回根据响应体匹配形成的对象
- headForHeaders() 发送HTTP HEAD请求,返回包含特定资源URL的HTTP头
- optionsForAllow() 发送HTTP OPTIONS请求,返回对特定URL的Allow头信息
- postForLocation() POST 数据到一个URL,返回新创建资源的URL
- put() PUT 资源到特定的URL