几种方式或说方案
Jdk本身提供 java.net 包的 HttpURLConnection
Apache提供HttpClient
Spring Web提供RestTemplate
以上都可以在java代码中模拟实现http请求,是随着技术的进步出来的,总体上越来越方便了,以后也可能会出现更高级、更方便的发起http请求的工具类。
Jdk本身提供 java.net 包的 HttpURLConnection
因为是jdk自带的,所以maven中不需要引入任何东西可以直接使用。
Apache提供HttpClient
Maven中需要引入apache相关包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
Spring Web提供RestTemplate
org.springframework.web.client.RestTemplate
项目中只需要加入spring-web的依赖就可以了。
★自己实践
背景及要求:get方式实现登录获取用户信息
启动本机的某项目。访问登录链接,从其返回信息中获取用户真实姓名realName信息。链接如下:
http://localhost:1008/LoginService/login?userName=admin&password=123
返回结果信息
{
"resultCode" : 0,
"result" : {
"userId" : 1,
"userName" : "admin",
"realName" : "admin",
"password" : "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3",
"isEnabled" : "1",
"mobilePhone" : null,
"createUser" : "sys",
"createDate" : "1970-01-01 00:00:00.0",
"updateUser" : "sys",
"updateDate" : "1970-01-01 00:00:00.0",
"expireDate" : "2050-01-01 00:00:00.0"
},
"msgId" : "6388f2f2-1fa8-42dc-b7dc-f650a5589ae1",
"errorMsg" : null
}
HttpURLConnection实现get请求
package com.ding.thirdService.httpURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import org.json.JSONException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
/**
*
* Description:使用 java.net 包的 HttpURLConnection 模拟 http 请求
*
*/
@RestController
@RequestMapping(value = "/javanet")
public class HttpURLConnectionController {
@RequestMapping(value = "/call")
public String call(@RequestParam(value = "userName") String userName,@RequestParam(value = "password") String password) throws JSONException, IOException {
URL url = new URL("http://localhost:1008/LoginService/login?userName="+ userName + "&password=" + password);//如果有参数,在网址中携带参数
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder builder = new StringBuilder();
while((line=br.readLine())!=null){
builder.append(line);
}
br.close();
isr.close();
is.close();
String data = builder.toString();
System.out.println(data);
if(data == null || data.length() == 0){
return "未获取数据";
}
/**
* 数据的接收的处理
*/
//判断请求是否成功JSONObject
Map<?, ?> maps = (Map<?, ?>)JSON.parse(data);
String resultCode = String.valueOf(maps.get("resultCode"));
//失败了
if(!(null != resultCode && resultCode.contains("0"))){
return "获取失败";
}
/**
* 成功的话则返回自定义的数据格式
*/
String detail = String.valueOf(maps.get("result"));
Map<?, ?> d = (Map<?, ?>)JSON.parse(detail);
return JSON.toJSONString(d.get("realName"));
}
}
HttpClient方式实现get请求
package com.ding.thirdService.httpClient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import org.json.JSONException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
/**
*
* Description:使用 Apache 包的 HttpClient 模拟 http 请求
*
*/
@RestController
@RequestMapping(value = "/client")
public class HttpClientController {
@RequestMapping(value = "/call")
public String call(@RequestParam(value = "userName") String userName,@RequestParam(value = "password") String password)
throws JSONException, IOException {
// 如果有参数,在网址中携带参数
URL url = new URL("http://localhost:1008/LoginService/login?userName="+ userName + "&password=" + password);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("encoding", "UTF-8");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("向服务器传递的参数");
bw.flush();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder builder = new StringBuilder();
while ((line = br.readLine()) != null) {
builder.append(line);
}
String data = builder.toString();
// 关闭资源
System.out.println(data);
if(data == null || data.length() == 0){
return "未获取数据";
}
/**
* 数据的接收的处理
*/
// 判断请求是否成功JSONObject
Map<?, ?> maps = (Map<?, ?>)JSON.parse(data);
String resultCode = String.valueOf(maps.get("resultCode"));
//失败了
if(!(null != resultCode && resultCode.contains("0"))){
return "获取失败";
}
/**
* 成功的话则返回自定义的数据格式
*/
String detail = String.valueOf(maps.get("result"));
Map<?, ?> d = (Map<?, ?>)JSON.parse(detail);
return JSON.toJSONString(d.get("realName"));
}
}
RestTemplate方式实现get请求
package com.ding.thirdService.restTemplate;
import java.util.Map;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSON;
/**
*
* Description:RestTemplate 使用
*
*/
@RestController
@RequestMapping(value = "/restTemplate")
public class RestTemplateController {
@Autowired
private RestTemplate restTemplate;
/**
*
* Description:RestTemplate 使用
* @param userName
* @param password
* @return
* @throws JSONException
*/
@RequestMapping(value = "/call")
public String call(@RequestParam(value = "userName") String userName,@RequestParam(value = "password") String password) throws JSONException {
String u = "http://localhost:1008/LoginService/login?userName="+ userName + "&password=" + password;
/**
* String格式接收数据
*/
String data = null;
try{
data = restTemplate.getForObject(u,String.class);
}catch(Exception e){
return e.toString();
}
System.out.println(data);
/**
* 数据的接收的处理
*/
//判断请求是否成功JSONObject
Map<?, ?> maps = (Map<?, ?>)JSON.parse(data);
String resultCode = String.valueOf(maps.get("resultCode"));
//失败了
if(!(null != resultCode && resultCode.contains("0"))){
return "获取失败";
}
/**
* 成功的话则返回自定义的数据格式
*/
String detail = String.valueOf(maps.get("result"));
Map<?, ?> d = (Map<?, ?>)JSON.parse(detail);
return JSON.toJSONString(d.get("realName"));
}
@RequestMapping(value = "/call2")
public Integer call2(@RequestParam(value = "jsonString") String jsonString) throws JSONException {
return 2;
}
}
RestTemplate配置类
package com.ding.thirdService.restTemplate.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig{
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(5000);//ms
factory.setConnectTimeout(15000);//ms
return factory;
}
}