Java 调用第三方接口方法
一、 通过JDK网络类Java.net.HttpURLConnection
1.java.net包下的原生java api提供的http请求
使用步骤:
1、通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)。
2、设置请求的参数。
3、发送请求。
4、以输入流的形式获取返回内容。
5、关闭输入流。
2.HttpClientUtil工具类
public class HttpClientUtil2 {
public static String doPost(String pathUrl, String data){
OutputStreamWriter out = null;
BufferedReader br = null;
String result = "";
try {
URL url = new URL(pathUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.connect();
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
out.write(data);
out.flush();
InputStream is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null){
result += str;
}
System.out.println(result);
is.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (out != null){
out.close();
}
if (br != null){
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String doGet(String pathUrl){
BufferedReader br = null;
String result = "";
try {
URL url = new URL(pathUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
conn.connect();
InputStream is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String str = "";
while ((str = br.readLine()) != null){
result += str;
}
System.out.println(result);
is.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (br != null){
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}
3.第三方api接口
@RestController
@RequestMapping("/api")
public class HelloWorld {
private static final Logger log= LoggerFactory.getLogger(HelloWorld.class);
@GetMapping ("/getHello")
public Result getHelloWord(){
log.info("进入到api接口.......");
return Result.success("hello world api get 接口数据");
}
@PostMapping("/postHello")
public Result postHelloWord(@RequestBody User user){
log.info("进入post 方法.....");
System.out.println(user.toString());
return Result.success("hello world api post接口数据");
}
}
4.测试类
@Test
public void testJDKApi(){
String s = HttpClientUtil2.doGet("http://localhost:9092/api/getHello");
System.out.println("get方法:"+s);
User user = new User();
user.setUname("胡萝卜");
user.setRole("普通用户");
String s1 = JsonUtil.toJson(user);
String postString = HttpClientUtil2.doPost("http://localhost:9092/api/postHello",s1);
System.out.println("post方法:"+postString);
}
结果:
二、通过Apache common封装好的HttpClient
1.引入依赖
<!--HttpClient-->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!--json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
2.httpClientUtil
public class HttpClientUtil {
public static String doGet(String url, String charset){
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
GetMethod getMethod = new GetMethod(url);
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String response = "";
try {
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK){
System.err.println("请求出错:" + getMethod.getStatusLine());
}
Header[] headers = getMethod.getResponseHeaders();
for (Header h: headers){
System.out.println(h.getName() + "---------------" + h.getValue());
}
byte[] responseBody = getMethod.getResponseBody();
response = new String(responseBody, charset);
System.out.println("-----------response:" + response);
} catch (HttpException e) {
System.out.println("请检查输入的URL!");
e.printStackTrace();
} catch (IOException e){
System.out.println("发生网络异常!");
}finally {
getMethod.releaseConnection();
}
return response;
}
public static String doPost(String url, JSONObject json){
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.addRequestHeader("accept", "*/*");
postMethod.addRequestHeader("connection", "Keep-Alive");
postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
StringRequestEntity param = new StringRequestEntity(json.getString("param"));
postMethod.setRequestEntity(param);
String res = "";
try {
int code = httpClient.executeMethod(postMethod);
if (code == 200){
byte[] responseBody = postMethod.getResponseBody();
res = new String(responseBody, "UTF-8");
System.out.println(res);
}
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
}
3.第三方api接口
@RestController
@RequestMapping("/api")
public class HelloWorld {
private static final Logger log= LoggerFactory.getLogger(HelloWorld.class);
@GetMapping ("/getHello")
public Result getHelloWord(){
log.info("进入到api接口.......");
return Result.success("hello world api get 接口数据");
}
@PostMapping("/postHello")
public Result postHelloWord(@RequestBody User user){
log.info("进入post 方法.....");
System.out.println(user.toString());
return Result.success("hello world api post接口数据");
}
}
4.测试类
@Test
public void testApi() {
String s = HttpClientUtil.doGet("http://localhost:9092/api/getHello", "UTF-8");
System.out.println("get方法:"+s);
User user = new User();
user.setUname("胡萝卜");
user.setRole("普通用户");
JSONObject jsonObject = new JSONObject();
String s1 = JsonUtil.toJson(user);
jsonObject.put("param",s1);
String postString = HttpClientUtil.doPost("http://localhost:9092/api/postHello", jsonObject);
System.out.println("post方法:"+postString);
}
结果:
三、通过Spring的RestTemplate
1.引入依赖
导入springboot的web包
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.RestTemplate配置类
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(15000);
factory.setReadTimeout(5000);
return factory;
}
}
3.RestTemplate实现类
@Component
public class RestTemplateToInterface {
@Autowired
private RestTemplate restTemplate;
public Result doGetWith1(String url){
ResponseEntity<Result> responseEntity = restTemplate.getForEntity(url, Result.class);
Result result = responseEntity.getBody();
return result;
}
public Result doGetWith2(String url){
Result result = restTemplate.getForObject(url, Result.class);
return result;
}
public String doPostWith1(String url,User user){
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, user, String.class);
String body = responseEntity.getBody();
return body;
}
public String doPostWith2(String url,User user){
String body = restTemplate.postForObject(url, user, String.class);
return body;
}
public String doExchange(String url, Integer age, String name){
HttpHeaders headers = new HttpHeaders();
String token = "asdfaf2322";
headers.add("authorization", token);
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject obj = new JSONObject();
obj.put("age", age);
obj.put("name", name);
HttpEntity<JSONObject> request = new HttpEntity<>(obj, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
String body = responseEntity.getBody();
return body;
}
}
4.第三方api接口
@RestController
@RequestMapping("/api")
public class HelloWorld {
private static final Logger log= LoggerFactory.getLogger(HelloWorld.class);
@GetMapping ("/getHello")
public Result getHelloWord(){
log.info("进入到api接口.......");
return Result.success("hello world api get 接口数据");
}
@PostMapping("/postHello")
public Result postHelloWord(@RequestBody User user){
log.info("进入post 方法.....");
System.out.println(user.toString());
return Result.success("hello world api post接口数据");
}
}
5.测试类
@Autowired
private RestTemplateToInterface restTemplateToInterface;
@Test
public void testSpringBootApi(){
Result result= restTemplateToInterface.doGetWith1("http://localhost:9092/api/getHello");
System.out.println("get结果:"+result);
User user = new User();
user.setUname("胡萝卜");
user.setRole("普通用户");
String s = restTemplateToInterface.doPostWith1("http://localhost:9092/api/postHello", user);
System.out.println("post结果:"+s);
}
结果:
|