python调用restful api接口的几种方式_Java调用RESTful接口的几种方式

前端一般通过Ajax来调用,后端调用的方式还是挺多的,比如HttpURLConnection,HttpClient,Spring的RestTemplate

服务端代码如下:

package com.demo.restful.service.impl;

import com.demo.restful.model.User;

import com.demo.restful.service.UserService;

import javax.ws.rs.GET;

import javax.ws.rs.Path;

import javax.ws.rs.PathParam;

import javax.ws.rs.Produces;

import javax.ws.rs.core.MediaType;

/**

* @Author:

* @Date: 2019/1/8 11:37

*/

@Path("user")

public class UserServiceImpl implements UserService {

@Override

@GET

@Path("getUser/{name}/{age}")

@Produces(MediaType.APPLICATION_JSON)

public String getUser(@PathParam("name") String name,@PathParam("age") Integer age) {

return new User(name,age).toString();

}

}

客户端的三种请求方式如下:

注:以下demo都是以GET请求为例

1.HttpURLConnection(首先需要引入httpclient包)

org.apache.httpcomponents

httpclient

4.5.6

测试代码

package com.demo.restful;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

/**

* @Author:

* @Date: 2019/1/9 11:12

*/

public class HttpUrlConnectionTest {

public static void main(String[] args) throws Exception {

String url = "http://localhost:8080/rest/user/getUser/xiaoming/18";

URL serverUrl = new URL(url);

HttpURLConnection connection = (HttpURLConnection) serverUrl.openConnection();

connection.setRequestMethod("GET");

if (connection.getResponseCode() != 200) {

throw new RuntimeException(

"HTTP GET Request Failed with Error code : "

+ connection.getResponseCode());

}

BufferedReader responseBuffer = new BufferedReader(

new InputStreamReader((connection.getInputStream())));

String output;

System.out.println("Output from Server: \n");

while ((output = responseBuffer.readLine()) != null) {

System.out.println(output);

}

connection.disconnect();

}

}

测试结果

2.HttpClient(首先需要引入httpclient包,POM同上)

测试代码

package com.demo.restful;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.util.stream.Collectors;

/**

* @Author:

* @Date: 2019/1/9 11:42

*/

public class HttpClientTest {

public static void main(String[] args) throws Exception {

HttpClient httpClient = HttpClients.createDefault();

HttpGet httpGet = new HttpGet("http://localhost:8080/rest/user/getUser/xiaoming/18");

HttpResponse execute = httpClient.execute(httpGet);

HttpEntity entity = execute.getEntity();

System.out.println(entity);

String result = new BufferedReader(new InputStreamReader(entity.getContent()))

.lines().collect(Collectors.joining("\n"));

System.out.println(result);

}

}

测试结果

3.RestTemplate(首先需要引入spring-webmvc包)

org.springframework

spring-webmvc

5.1.3.RELEASE

测试代码

第一步:配置web.xml

Archetype Created Web Application

restful-client

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

spring.xml

restful-client

/

第二步:配置Spring注解扫描

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

第三步:编写controller

package com.demo.restful.controller;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.*;

import org.springframework.web.client.RestTemplate;

/**

* @Author:

* @Date: 2019/1/9 14:56

*/

@Controller

public class RestTemplateController {

@Autowired

private RestTemplate restTemplate;

//手动将RestTemplate加入Spring容器中

@Bean

public RestTemplate restTemplate(){

return new RestTemplate();

}

@RequestMapping("/getUser.json")

@ResponseBody

public String getUser(){

String url = "http://localhost:8080/rest/user/getUser/xiaoming/18";

String forObject = restTemplate.getForObject(url, String.class);

return forObject;

}

}

浏览器运行结果

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值