1, Basic introduction

Restful Interface call , The front end is generally used ajax call , There are many methods that can be used by the back end ,

This time, we will introduce three types :

1.HttpURLConnection Realization

2.HttpClient Realization

3.Spring Of RestTemplate

2,HttpURLConnection Realization

@Controller
public class RestfulAction { @Autowired
private UserService userService;
// modify
@RequestMapping(value = "put/{param}", method = RequestMethod.PUT)
public @ResponseBody String put(@PathVariable String param) {
return "put:" + param;
}
// newly added
@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;
}
// Delete
@RequestMapping(value = "delete/{param}", method = RequestMethod.DELETE)
public @ResponseBody String delete(@PathVariable String param) {
return "delete:" + param;
}
// lookup
@RequestMapping(value = "get/{param}", method = RequestMethod.GET)
public @ResponseBody String get(@PathVariable String param) {
return "get:" + param;
}
// HttpURLConnection Way to call Restful Interface
// Call interface
@RequestMapping(value = "dealCon/{param}")
public @ResponseBody String dealCon(@PathVariable String param) {
try {
String url = "http://localhost:8080/tao-manager-web/";
url+=(param+"/xxx");
URL restServiceURL = new URL(url);
HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL
.openConnection();
//param Enter lowercase , convert to GET POST DELETE PUT
httpConnection.setRequestMethod(param.toUpperCase());
// httpConnection.setRequestProperty("Accept", "application/json");
if("post".equals(param)){
// Turn on the output switch
httpConnection.setDoOutput(true);
// httpConnection.setDoInput(true); // Pass parameters
String input = "&id="+ URLEncoder.encode("abc", "UTF-8");
input+="&name="+ URLEncoder.encode(" Ah ah ", "UTF-8");
OutputStream outputStream = httpConnection.getOutputStream();
outputStream.write(input.getBytes());
outputStream.flush();
}
if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException(
"HTTP GET Request Failed with Error code : "
+ httpConnection.getResponseCode());
}
BufferedReader responseBuffer = new BufferedReader(
new InputStreamReader((httpConnection.getInputStream())));
String output;
System.out.println("Output from Server: \n");
while ((output = responseBuffer.readLine()) != null) {
System.out.println(output);
}
httpConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73

3.HttpClient Realization

package com.taozhiye.controller;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.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 com.taozhiye.entity.User;
import com.taozhiye.service.UserService;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List; @Controller
public class RestfulAction {
@Autowired
private UserService userService;
// modify
@RequestMapping(value = "put/{param}", method = RequestMethod.PUT)
public @ResponseBody String put(@PathVariable String param) {
return "put:" + param;
}
// newly added
@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;
}
// Delete
@RequestMapping(value = "delete/{param}", method = RequestMethod.DELETE)
public @ResponseBody String delete(@PathVariable String param) {
return "delete:" + param;
}
// lookup
@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);
u.setUsername(" Love, love ");
return u;
}
@RequestMapping(value = "dealCon2/{param}")
public @ResponseBody User dealCon2(@PathVariable String param) {
User user = null;
try {
HttpClient client = HttpClients.createDefault();
if("get".equals(param)){
HttpGet request = new HttpGet("http://localhost:8080/tao-manager-web/get/"
+" Ah ah ");
request.setHeader("Accept", "application/json");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
ObjectMapper mapper = new ObjectMapper();
user = mapper.readValue(entity.getContent(), User.class);
}else if("post".equals(param)){
HttpPost request2 = new HttpPost("http://localhost:8080/tao-manager-web/post/xxx");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("id", " Ah ah "));
nvps.add(new BasicNameValuePair("name", "secret"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvps, "GBK");
request2.setEntity(formEntity);
HttpResponse response2 = client.execute(request2);
HttpEntity entity = response2.getEntity();
ObjectMapper mapper = new ObjectMapper();
user = mapper.readValue(entity.getContent(), User.class);
}else if("delete".equals(param)){ }else if("put".equals(param)){ }
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103

4.Spring Of RestTemplate

springmvc.xml increase

<!-- To configure 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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

controller

@Controller
public class RestTemplateAction { @Autowired
private RestTemplate template; @RequestMapping("RestTem")
public @ResponseBody User RestTem(String method) {
User user = null;
// lookup
if ("get".equals(method)) {
user = template.getForObject(
"http://localhost:8080/tao-manager-web/get/{id}",
User.class, " Woo woo "); //getForEntity And getForObject The difference is that you can get the return value and status 、 First class information
ResponseEntity<User> re = template.
getForEntity("http://localhost:8080/tao-manager-web/get/{id}",
User.class, " Woo woo ");
System.out.println(re.getStatusCode());
System.out.println(re.getBody().getUsername()); // newly added
} 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", " Ah ah ");
postParameters.add("name", " Ministry version ");
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
postParameters, headers);
user = template.postForObject(
"http://localhost:8080/tao-manager-web/post/aaa", requestEntity,
User.class);
// Delete
} else if ("delete".equals(method)) {
template.delete("http://localhost:8080/tao-manager-web/delete/{id}","aaa");
// modify
} else if ("put".equals(method)) {
template.put("http://localhost:8080/tao-manager-web/put/{id}",null,"bbb");
}
return user; }
}

Three ways to achieve java call Restful More articles on interfaces

  1. Java call RestFul Interface

    Use Java call RestFul Interface , With POST Request as an example , Here are some ways : One . adopt HttpURLConnection call 1 public String postRequest(String url ...

  2. JAVA Write JSON Three ways ,java Object turn json data

    JAVA Write JSON Three ways ,java Object turn json data from :http://www.xdx97.com/#/single?bid=5afe2ff9-8cd1-67cf-e7bc-437b74c07a ...

  3. Array k Three methods of translation (java)

    Code up , This paper uses three methods to achieve , The time complexity is different , The complexity of space is o(1): public class ArrayKMove { /** * problem : Left of array k translation ,k Less than array length * @param ar ...

  4. java call restful Interface method

    Restful Interface call , The front end is generally used ajax call , The methods that can be used by the back end are as follows : 1.HttpURLConnection Realization 2.HttpClient Realization 3.Spring Of RestTemplate

  5. Java Methods by RestTemplate call restful Interface

    background : project A The project needs to be called inside the code B One of the restful Interface , The interface is POST The way ,header in  Authorization For custom content , The main transmission content is encapsulated in body in , So I used RestTemp ...

  6. Top k Discussion of problems ( Three ways java Realization and application scope )

    In many written tests and interviews , I like to study Top K. The following gives three implementation methods and practical scope from their own experience . Merger Law This method is suitable for several arrays in order , Come and ask for Top k. The time complexity is O(k*m).(m: Is the number of arrays ). Concrete facts ...

  7. Java call Restful API Several ways of interface --HTTPS

    Abstract : There is a need recently , Provide customers with some Restful API Interface ,QA Use postman To test , however postman Test interface and interface of java Calls are similar but not the same , So I want to write a program to test Restful ...

  8. Java Realization ping The three methods and methods of function analysis Linux The distinction between

    Most of the first half turned from :https://blog.csdn.net/futudeniaodan/article/details/52317650 Test the running state of the equipment , Some use ping The way to detect . So we need to ...

  9. Three methods to call Restful Interface

    1. Basic introduction Restful Interface call , The front end is generally used ajax call , There are many methods that can be used by the back end , This time, we will introduce three types : 1.HttpURLConnection Realization 2.HttpClient Realization 3.Spring ...

Random recommendation

  1. Android Payment access ( Two ): Mobile game base

    The original address :http://blog.csdn.net/simdanfeg/article/details/9011863 In the first part, Bowen went with everyone to Alipay payment. , Today, let's take a look at mobile payment . As we all know, the current payment channel ...

  2. The conversion time is “XX Minutes ago ”

    public static string getTimeAgo(string strDate) { string strTime = string.Empty; if (clsCommon.IsDat ...

  3. Iptables Network connection restriction, attack protection and related settings

    [ Note arrangement ]Iptables Network connection restriction, attack protection and related settings 1. Limit each IP Connect HTTP Maximum concurrency 50 Number of connections iptables -A INPUT -p tcp --dport 80 -m conn ...

  4. be based on visual Studio2013 solve C One of the questions in the language contest 1045 Print results

       subject Solution code and comments /* function : Use records to describe a student's grades , The content includes : full name . Student number . Math grades and PASCAL achievement . Ask for feedback on a group 10 The results of each student were statistically processed : 1) Calculate the total number of students ...

  5. flock - Bing Ying dictionary

    flock - Bing Ying dictionary beautiful [flɑk] Britain [flɒk] v. Gather : to cluster around : Swarms n.( Sheep or birds ) Group :( Especially of the same kind ) a crowd of Online herding : A lot of : flock of sheep , a group Deformed complex number :flocks: past participle :flocked: present ...

  6. Numpy Data types and basic operations

    Numpy data type bool Boolean type stored in one bit ( The value is TRUE or FALSE) inti Integer whose precision is determined by the platform ( It's usually int32 or int64) int8 Integers , The scope is 128 to 127 int1 ...

  7. C# new function -- Named parameters

    Naming parameters can potentially change the way code is written . This new feature makes the code easier to read and understand . for example , to glance at System.IO In the namespace File.Copy() Method , It is generally constructed as File.Copy(@"C:\m ...

  8. stay EXT In the frame , Use JS File settings UEditor The text box , There are many new contents , Page variant , No scrollbars , Causes the operation to be unable to proceed .

    find UEditor Configuration file for :ueditor.config.js( This is the beginning of my project UEditor Profile name for ) Parameter settings found autoHeightEnabled Auto grow parameter , The default is TRUE When default ...

  9. node Learning notes _01 Environment building

    One . Download and install nvm (node Version Manager ), Convenient for later version switching nvm list            -> see node edition ( The best version is 8.0 above , Otherwise, in the vsCode Breakpoint debugging can't get in , Follow node edition ...

  10. hdu 5310( greedy )

    The question : Want to buy n A souvenir , The unit price p element , There is a group purchase price m individual q element , How to buy the least money This is BC Anniversary first question , Water topic , Primary school math problems , Just look at n A souvenir list . Overall buy group purchase, and then buy a fraction of the unit price . It doesn't matter if you buy more than the group purchase price , And then directly ...