java调⽤Restful接⼝的三种⽅法⽬录
1,基本介绍
2,HttpURLConnection实现
3.HttpClient实现
4.Spring的RestTemplate
1,基本介绍
Restful接⼝的调⽤,前端⼀般使⽤ajax调⽤,后端可以使⽤的⽅法⽐较多,
  本次介绍三种:
    1.HttpURLConnection实现
    2.HttpClient实现
    3.Spring的RestTemplate     
2,HttpURLConnection实现
@Controller
public class RestfulAction {
@Autowired
private UserService userService;
// 修改
@RequestMapping(value = "put/{param}", method = RequestMethod.PUT)
public @ResponseBody String put(@PathVariable String param) {
return "put:" + param;
}
// 新增
@RequestMapping(value = "post/{param}", method = RequestMethod.POST)
public @ResponseBody String post(@PathVariable String param,String id,String name) {
System.out.println("id:"+id);
System.out.println("name:"+name);
return "post:" + param;
}
// 删除
@RequestMapping(value = "delete/{param}", method = RequestMethod.DELETE)
public @ResponseBody String delete(@PathVariable String param) {
return "delete:" + param;
}
/
/ 查
@RequestMapping(value = "get/{param}", method = RequestMethod.GET)
public @ResponseBody String get(@PathVariable String param) {
return "get:" + param;
}
// HttpURLConnection ⽅式调⽤Restful接⼝
// 调⽤接⼝
@RequestMapping(value = "dealCon/{param}")
public @ResponseBody String dealCon(@PathVariable String param) {
try {
String url = "localhost:8080/tao-manager-web/";
url+=(param+"/xxx");
URL restServiceURL = new URL(url);
HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL
.openConnection();
//param 输⼊⼩写,转换成 GET POST DELETE PUT
httpConnection.UpperCase());
//            httpConnection.setRequestProperty("Accept", "application/json");
if("post".equals(param)){
//打开输出开关
httpConnection.setDoOutput(true);
//                httpConnection.setDoInput(true);
/
/传递参数
String input = "&id="+ de("abc", "UTF-8");
input+="&name="+ de("啊啊啊", "UTF-8");
OutputStream outputStream = OutputStream();
outputStream.Bytes());
outputStream.flush();
}
if (ResponseCode() != 200) {
throw new RuntimeException(
"HTTP GET Request Failed with Error code : "
+ ResponseCode());
}
BufferedReader responseBuffer = new BufferedReader(
new InputStreamReader((InputStream())));
String output;
System.out.println("Output from Server:  \n");
while ((output = adLine()) != null) {
System.out.println(output);
}
httpConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
}
3.HttpClient实现
package ller;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.ity.UrlEncodedFormEntity;
import org.apache.hods.HttpDelete;
import org.apache.hods.HttpGet;
import org.apache.hods.HttpPost;
import org.apache.hods.HttpPut;
import org.apache.http.impl.client.HttpClients;
import org.ssage.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.databind.ObjectMapper;
import ity.User;
import com.taozhiye.service.UserService;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.HttpURLConnection;
import java.MalformedURLException;
import java.URL;
import java.URLEncoder;
import java.util.ArrayList;
import java.util.List;
@Controller
public class RestfulAction {
@Autowired
private UserService userService;
// 修改
@RequestMapping(value = "put/{param}", method = RequestMethod.PUT)
public @ResponseBody String put(@PathVariable String param) {
return "put:" + param;
}
// 新增
@RequestMapping(value = "post/{param}", method = RequestMethod.POST)
public @ResponseBody User post(@PathVariable String param,String id,String name) {        User u = new User();
System.out.println(id);
System.out.println(name);
u.setName(id);
u.setPassword(name);
u.setEmail(id);
u.setUsername(name);
return u;
}
// 删除
@RequestMapping(value = "delete/{param}", method = RequestMethod.DELETE)
public @ResponseBody String delete(@PathVariable String param) {
return "delete:" + param;
}
// 查
@RequestMapping(value = "get/{param}", method = RequestMethod.GET)
public @ResponseBody User get(@PathVariable String param) {
User u = new User();
u.setName(param);
u.setPassword(param);
u.setEmail(param);
restful接口详解
u.setUsername("爱爱啊");
return u;
}
@RequestMapping(value = "dealCon2/{param}")
public @ResponseBody User dealCon2(@PathVariable String param) {
User user = null;
try {
HttpClient client = ateDefault();
if("get".equals(param)){
HttpGet request = new HttpGet("localhost:8080/tao-manager-web/get/"
+"啊啊啊");
request.setHeader("Accept", "application/json");
HttpResponse response = ute(request);
HttpEntity entity = Entity();
ObjectMapper mapper = new ObjectMapper();
user = Content(), User.class);
}else if("post".equals(param)){
HttpPost request2 = new HttpPost("localhost:8080/tao-manager-web/post/xxx");                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("id", "啊啊啊"));
nvps.add(new BasicNameValuePair("name", "secret"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvps, "GBK");
request2.setEntity(formEntity);
HttpResponse response2 = ute(request2);
HttpEntity entity = Entity();
ObjectMapper mapper = new ObjectMapper();
user = Content(), User.class);
}else if("delete".equals(param)){
}else if("put".equals(param)){
}
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
}
4.Spring的RestTemplate
<!-- 配置RestTemplate -->
<!--Http client Factory -->
<bean id="httpClientFactory"
class="org.springframework.http.client.SimpleClientHttpRequestFactory">
<property name="connectTimeout" value="10000" />
<property name="readTimeout" value="10000" />
</bean>
<!--RestTemplate -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg ref="httpClientFactory" />
</bean>
controller
@Controller
public class RestTemplateAction {
@Autowired
private RestTemplate template;
@RequestMapping("RestTem")
public @ResponseBody User RestTem(String method) {
User user = null;
//查
if ("get".equals(method)) {
user = ForObject(
"localhost:8080/tao-manager-web/get/{id}",
User.class, "呜呜呜呜");
//getForEntity与getForObject的区别是可以获取返回值和状态、头等信息
ResponseEntity<User> re = template.
getForEntity("localhost:8080/tao-manager-web/get/{id}",
User.class, "呜呜呜呜");
System.out.StatusCode());
System.out.Body().getUsername());
//新增
} else if ("post".equals(method)) {
HttpHeaders headers = new HttpHeaders();
headers.add("X-Auth-Token", UUID.randomUUID().toString());
MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();
postParameters.add("id", "啊啊啊");
postParameters.add("name", "部版本");
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
postParameters, headers);
user = template.postForObject(
"localhost:8080/tao-manager-web/post/aaa", requestEntity,
User.class);
//删除
} else if ("delete".equals(method)) {
template.delete("localhost:8080/tao-manager-web/delete/{id}","aaa");
//修改
} else if ("put".equals(method)) {
template.put("localhost:8080/tao-manager-web/put/{id}",null,"bbb");
}
return user;
}
}
到此这篇关于java调⽤Restful接⼝的三种⽅法的⽂章就介绍到这了,更多相关java调⽤Restful接⼝内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。