├── .gitattributes ├── LICENSE ├── README.md ├── restTemplateBuilderDemo ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── gl │ │ │ └── restTemplateBuilderDemo │ │ │ ├── MainController.java │ │ │ ├── RestTemplateBuilderDemo.java │ │ │ ├── User.java │ │ │ └── config │ │ │ ├── Config.java │ │ │ ├── GoogleTest.java │ │ │ ├── MyClientHttpResponse.java │ │ │ ├── MyRequestInterceptor.java │ │ │ └── MyRestTemplateCustomizer.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── com │ └── gl │ └── userManagementClient │ └── RestTemplateBuilderDemoApplicationTests.java └── userManagementClient ├── .gitignore ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── gl │ │ └── userManagementClient │ │ ├── ForEntityMethodOfRestTemplateDemo.java │ │ ├── ForObjectMethodOfRestTemplateDemo.java │ │ ├── User.java │ │ └── UserManagementClient.java └── resources │ └── application.properties └── test └── java └── com └── gl └── userManagementClient └── UserManagementClientApplicationTests.java /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Green Learner 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RestTemplate 2 | Microservices communication using #Spring #RestTemplate. The code in this repository has been explained in below videos. Follow them topic wise and in case of doubt comment in the 'comment' section of youtube video. 3 | Hope you'll learn and enjoy learning microservices with me :) 4 | 5 | ## Exchange() method of Rest Template - calling Http GET endpoint of external REST service 6 | Explained in video with details - https://youtu.be/5WXk88r9T90 7 | 8 | ## Exchange() method of Rest Template - calling Http POST/PUT/DELETE endpoint of external REST service 9 | Youtube video for explanation - https://youtu.be/RHplGVRKwlc 10 | 11 | ## getForObject(), postForObject(), getForEntity(), postForEntity(), postForLocation, put(), delete() methods of RestTemplate 12 | Code is in the present repository and to see the explanation of code watch - https://youtu.be/m4VvvqeTngU 13 | 14 | ## How to create instance of RestTemplate using RestTemplateBuilder 15 | Watch video to get insights - https://youtu.be/_1DJo1qfwP0 16 | 17 | ## How to add base URL in RestTemplate 18 | Watch video - https://youtu.be/7RBp4bCQWZI 19 | ## How to Add timout in RestTemplate 20 | Watch video - https://youtu.be/H00jO2y0kXM 21 | 22 | ## How to add interceptor in RestTemplate for centralized logging of request and response 23 | https://youtu.be/WaxS4EQO8WQ 24 | -------------------------------------------------------------------------------- /restTemplateBuilderDemo/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/** 6 | !**/src/test/** 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | 17 | ### IntelliJ IDEA ### 18 | .idea 19 | *.iws 20 | *.iml 21 | *.ipr 22 | out/ 23 | 24 | ### NetBeans ### 25 | /nbproject/private/ 26 | /nbbuild/ 27 | /dist/ 28 | /nbdist/ 29 | /.nb-gradle/ 30 | 31 | ### VS Code ### 32 | .vscode/ 33 | -------------------------------------------------------------------------------- /restTemplateBuilderDemo/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.1.7.RELEASE' 3 | id 'java' 4 | } 5 | 6 | apply plugin: 'io.spring.dependency-management' 7 | 8 | group = 'com.gl' 9 | version = '0.0.1-SNAPSHOT' 10 | sourceCompatibility = '1.8' 11 | 12 | repositories { 13 | mavenCentral() 14 | } 15 | 16 | dependencies { 17 | implementation 'org.springframework.boot:spring-boot-starter-web' 18 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 19 | } 20 | -------------------------------------------------------------------------------- /restTemplateBuilderDemo/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefarm0/RestTemplate/91d77dd2a0571594193c9c00aeee8c1288ae42f9/restTemplateBuilderDemo/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /restTemplateBuilderDemo/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun Aug 18 20:04:37 IST 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip 7 | -------------------------------------------------------------------------------- /restTemplateBuilderDemo/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS='"-Xmx64m"' 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /restTemplateBuilderDemo/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS="-Xmx64m" 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /restTemplateBuilderDemo/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'restTemplateBuilderDemo' 2 | -------------------------------------------------------------------------------- /restTemplateBuilderDemo/src/main/java/com/gl/restTemplateBuilderDemo/MainController.java: -------------------------------------------------------------------------------- 1 | package com.gl.restTemplateBuilderDemo; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | import org.springframework.web.client.RestTemplate; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * @author - GreenLearner(https://www.youtube.com/channel/UCaH2MTg94hrJZTolW01a3ZA) 12 | */ 13 | 14 | @RestController 15 | public class MainController { 16 | 17 | @Autowired 18 | private RestTemplate restTemplate; 19 | 20 | @GetMapping("/userList") 21 | List getUserList(){ 22 | return restTemplate.getForObject("/users", 23 | List.class); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /restTemplateBuilderDemo/src/main/java/com/gl/restTemplateBuilderDemo/RestTemplateBuilderDemo.java: -------------------------------------------------------------------------------- 1 | package com.gl.restTemplateBuilderDemo; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * Author - Green Learner(https://facebook.com/greenlearner)
8 | * Official youtube channel - https://www.youtube.com/channel/UCaH2MTg94hrJZTolW01a3ZA
9 | */ 10 | 11 | @SpringBootApplication 12 | public class RestTemplateBuilderDemo { 13 | 14 | public static void main(String[] args) { 15 | SpringApplication.run(RestTemplateBuilderDemo.class, args); 16 | 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /restTemplateBuilderDemo/src/main/java/com/gl/restTemplateBuilderDemo/User.java: -------------------------------------------------------------------------------- 1 | package com.gl.restTemplateBuilderDemo; 2 | 3 | 4 | public class User { 5 | 6 | private Long id; 7 | 8 | private String firstName; 9 | 10 | private String lastName; 11 | 12 | private String gender; 13 | 14 | private String address; 15 | 16 | public Long getId() { 17 | return id; 18 | } 19 | 20 | public void setId(Long id) { 21 | this.id = id; 22 | } 23 | 24 | public String getFirstName() { 25 | return firstName; 26 | } 27 | 28 | public void setFirstName(String firstName) { 29 | 30 | this.firstName = firstName; 31 | } 32 | 33 | public String getAddress() { 34 | return address; 35 | } 36 | 37 | public void setAddress(String address) { 38 | this.address = address; 39 | } 40 | 41 | public String getLastName() { 42 | return lastName; 43 | } 44 | 45 | public void setLastName(String lastName) { 46 | this.lastName = lastName; 47 | } 48 | 49 | public String getGender() { 50 | return gender; 51 | } 52 | 53 | public void setGender(String gender) { 54 | this.gender = gender; 55 | } 56 | 57 | @Override 58 | public String toString() { 59 | return "User{" + 60 | "id=" + id + 61 | ", firstName='" + firstName + '\'' + 62 | ", lastName='" + lastName + '\'' + 63 | ", gender='" + gender + '\'' + 64 | ", address='" + address + '\'' + 65 | '}'; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /restTemplateBuilderDemo/src/main/java/com/gl/restTemplateBuilderDemo/config/Config.java: -------------------------------------------------------------------------------- 1 | package com.gl.restTemplateBuilderDemo.config; 2 | 3 | import org.springframework.boot.web.client.RestTemplateBuilder; 4 | import org.springframework.boot.web.client.RestTemplateCustomizer; 5 | import org.springframework.boot.web.client.RootUriTemplateHandler; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.context.annotation.DependsOn; 9 | import org.springframework.web.client.RestTemplate; 10 | import org.springframework.web.util.UriTemplateHandler; 11 | 12 | import java.time.Duration; 13 | 14 | /** 15 | * @author - GreenLearner(https://www.youtube.com/channel/UCaH2MTg94hrJZTolW01a3ZA) 16 | */ 17 | 18 | @Configuration 19 | public class Config { 20 | @Bean 21 | public RestTemplate restTemplate(RestTemplateBuilder builder) { 22 | UriTemplateHandler uriTemplateHandler = new RootUriTemplateHandler("http://localhost:8083/springDataDemo"); 23 | return builder 24 | .uriTemplateHandler(uriTemplateHandler) 25 | .setReadTimeout(Duration.ofMillis(2000)) 26 | .build(); 27 | } 28 | 29 | @Bean 30 | public MyRequestInterceptor myRequestInterceptor() { 31 | return new MyRequestInterceptor(); 32 | } 33 | 34 | @Bean 35 | public MyRestTemplateCustomizer restTemplateCustomizer() { 36 | return new MyRestTemplateCustomizer(); 37 | } 38 | 39 | @Bean 40 | @DependsOn("restTemplateCustomizer") 41 | public RestTemplateBuilder restTemplateBuilder(RestTemplateCustomizer restTemplateCustomizer) { 42 | return new RestTemplateBuilder(restTemplateCustomizer); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /restTemplateBuilderDemo/src/main/java/com/gl/restTemplateBuilderDemo/config/GoogleTest.java: -------------------------------------------------------------------------------- 1 | package com.gl.restTemplateBuilderDemo.config; 2 | 3 | import org.springframework.web.client.RestTemplate; 4 | 5 | /** 6 | * @author - GreenLearner(https://www.youtube.com/channel/UCaH2MTg94hrJZTolW01a3ZA) 7 | */ 8 | public class GoogleTest { 9 | public static void main(String[] args) { 10 | RestTemplate rt = new RestTemplate(); 11 | 12 | String url = "https://maps.googleapis.com/maps/api/geocode/json?address="; 13 | String address = "india"; 14 | String key = "&key=custom-key";//"AIzaSyAX_1d4cEaA50VZDg6BIJ_TSnncbLWiegY"; 15 | url=url+address+key; 16 | System.out.println(url); 17 | String response = rt.getForObject(url, String.class); 18 | System.out.println(response); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /restTemplateBuilderDemo/src/main/java/com/gl/restTemplateBuilderDemo/config/MyClientHttpResponse.java: -------------------------------------------------------------------------------- 1 | package com.gl.restTemplateBuilderDemo.config; 2 | 3 | import org.apache.tomcat.util.http.fileupload.IOUtils; 4 | import org.springframework.http.HttpHeaders; 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.http.client.ClientHttpResponse; 7 | 8 | import java.io.*; 9 | 10 | /** 11 | * @author - GreenLearner(https://www.youtube.com/channel/UCaH2MTg94hrJZTolW01a3ZA) 12 | */ 13 | public class MyClientHttpResponse implements ClientHttpResponse { 14 | 15 | private ClientHttpResponse clientHttpResponse; 16 | private byte[] body = null; 17 | 18 | public MyClientHttpResponse(ClientHttpResponse clientHttpResponse) { 19 | this.clientHttpResponse = clientHttpResponse; 20 | } 21 | 22 | @Override 23 | public HttpStatus getStatusCode() throws IOException { 24 | return clientHttpResponse.getStatusCode(); 25 | } 26 | 27 | @Override 28 | public int getRawStatusCode() throws IOException { 29 | return clientHttpResponse.getRawStatusCode(); 30 | } 31 | 32 | 33 | @Override 34 | public String getStatusText() throws IOException { 35 | return clientHttpResponse.getStatusText(); 36 | } 37 | 38 | 39 | @Override 40 | public void close() { 41 | clientHttpResponse.close(); 42 | } 43 | 44 | @Override 45 | public InputStream getBody() throws IOException { 46 | if (body != null) { 47 | return new ByteArrayInputStream(body); 48 | } 49 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 50 | IOUtils.copyLarge(clientHttpResponse.getBody(), outputStream); 51 | body = outputStream.toByteArray(); 52 | return new ByteArrayInputStream(body); 53 | } 54 | 55 | @Override 56 | public HttpHeaders getHeaders() { 57 | return clientHttpResponse.getHeaders(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /restTemplateBuilderDemo/src/main/java/com/gl/restTemplateBuilderDemo/config/MyRequestInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.gl.restTemplateBuilderDemo.config; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.http.HttpRequest; 6 | import org.springframework.http.client.ClientHttpRequestExecution; 7 | import org.springframework.http.client.ClientHttpRequestInterceptor; 8 | import org.springframework.http.client.ClientHttpResponse; 9 | import sun.misc.IOUtils; 10 | 11 | import java.io.*; 12 | import java.nio.charset.StandardCharsets; 13 | 14 | /** 15 | * @author - GreenLearner(https://www.youtube.com/channel/UCaH2MTg94hrJZTolW01a3ZA) 16 | */ 17 | public class MyRequestInterceptor implements ClientHttpRequestInterceptor { 18 | private Logger logger = LoggerFactory.getLogger(MyRequestInterceptor.class); 19 | 20 | @Override 21 | public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { 22 | 23 | logger.info("Request details"); 24 | logger.info(" URI - {}", request.getURI()); 25 | logger.info("Headers - {}", request.getHeaders()); 26 | logger.info("Method - {}", request.getMethod()); 27 | //request. 28 | 29 | ClientHttpResponse response = execution.execute(request, body); 30 | 31 | MyClientHttpResponse myClientHttpResponse = new MyClientHttpResponse(response); 32 | 33 | logger.info("Response details"); 34 | logger.info("status -{}", myClientHttpResponse.getStatusCode()); 35 | logger.info("Body -{}", getResponseBody(myClientHttpResponse.getBody())); 36 | 37 | return myClientHttpResponse; 38 | } 39 | 40 | private String getResponseBody(InputStream responseBody) { 41 | 42 | StringBuilder inputStringBuilder = new StringBuilder(); 43 | 44 | try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(responseBody, StandardCharsets.UTF_8))) 45 | { 46 | String line = bufferedReader.readLine(); 47 | while (line != null) { 48 | inputStringBuilder.append(line); 49 | inputStringBuilder.append('\n'); 50 | line = bufferedReader.readLine(); 51 | } 52 | return inputStringBuilder.toString(); 53 | } catch (IOException e) { 54 | e.printStackTrace(); 55 | return null; 56 | } 57 | //IOUtils. 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /restTemplateBuilderDemo/src/main/java/com/gl/restTemplateBuilderDemo/config/MyRestTemplateCustomizer.java: -------------------------------------------------------------------------------- 1 | package com.gl.restTemplateBuilderDemo.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.boot.web.client.RestTemplateCustomizer; 5 | import org.springframework.web.client.RestTemplate; 6 | 7 | /** 8 | * @author - GreenLearner(https://www.youtube.com/channel/UCaH2MTg94hrJZTolW01a3ZA) 9 | */ 10 | public class MyRestTemplateCustomizer implements RestTemplateCustomizer { 11 | 12 | @Autowired 13 | private MyRequestInterceptor myRequestInterceptor; 14 | 15 | @Override 16 | public void customize(RestTemplate restTemplate) { 17 | restTemplate.getInterceptors().add(myRequestInterceptor); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /restTemplateBuilderDemo/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /restTemplateBuilderDemo/src/test/java/com/gl/userManagementClient/RestTemplateBuilderDemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.gl.userManagementClient; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class RestTemplateBuilderDemoApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /userManagementClient/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/** 6 | !**/src/test/** 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | 17 | ### IntelliJ IDEA ### 18 | .idea 19 | *.iws 20 | *.iml 21 | *.ipr 22 | out/ 23 | 24 | ### NetBeans ### 25 | /nbproject/private/ 26 | /nbbuild/ 27 | /dist/ 28 | /nbdist/ 29 | /.nb-gradle/ 30 | 31 | ### VS Code ### 32 | .vscode/ 33 | -------------------------------------------------------------------------------- /userManagementClient/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.1.7.RELEASE' 3 | id 'java' 4 | } 5 | 6 | apply plugin: 'io.spring.dependency-management' 7 | 8 | group = 'com.gl' 9 | version = '0.0.1-SNAPSHOT' 10 | sourceCompatibility = '1.8' 11 | 12 | repositories { 13 | mavenCentral() 14 | } 15 | 16 | dependencies { 17 | implementation 'org.springframework.boot:spring-boot-starter-web' 18 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 19 | } 20 | -------------------------------------------------------------------------------- /userManagementClient/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefarm0/RestTemplate/91d77dd2a0571594193c9c00aeee8c1288ae42f9/userManagementClient/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /userManagementClient/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /userManagementClient/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS='"-Xmx64m"' 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /userManagementClient/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS="-Xmx64m" 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /userManagementClient/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'userManagementClient' 2 | -------------------------------------------------------------------------------- /userManagementClient/src/main/java/com/gl/userManagementClient/ForEntityMethodOfRestTemplateDemo.java: -------------------------------------------------------------------------------- 1 | package com.gl.userManagementClient; 2 | 3 | import org.springframework.http.HttpHeaders; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.http.ResponseEntity; 6 | import org.springframework.web.client.RestTemplate; 7 | 8 | import java.net.URI; 9 | import java.util.List; 10 | 11 | /** 12 | * @author - GreenLearner(https://www.youtube.com/channel/UCaH2MTg94hrJZTolW01a3ZA) 13 | */ 14 | public class ForEntityMethodOfRestTemplateDemo { 15 | private String baseUrl = "http://localhost:8083/springDataDemo/"; 16 | 17 | RestTemplate restTemplate= new RestTemplate(); 18 | 19 | public void driverMethod(){ 20 | System.out.println("*********** forEntity() methods demo ***********"); 21 | getSingleObject(); 22 | getListObject(); 23 | addUser(); 24 | deleteUser(); 25 | updateUser(); 26 | } 27 | private void getSingleObject() { 28 | String url = baseUrl + "/user/5"; 29 | ResponseEntity user = restTemplate.getForEntity(url, String.class); 30 | HttpStatus statusCode = user.getStatusCode(); 31 | System.out.println("status code - " + statusCode); 32 | String userDetails = user.getBody(); 33 | System.out.println("response body - " + userDetails); 34 | HttpHeaders responseHeaders = user.getHeaders(); 35 | System.out.println("response Headers - " + responseHeaders); 36 | } 37 | 38 | private void getListObject() { 39 | String url = baseUrl + "/users"; 40 | ResponseEntity user = restTemplate.getForEntity(url, List.class); 41 | HttpStatus statusCode = user.getStatusCode(); 42 | System.out.println("status code - " + statusCode); 43 | List userDetails = user.getBody(); 44 | System.out.println("response body - " + userDetails); 45 | HttpHeaders responseHeaders = user.getHeaders(); 46 | System.out.println("response Headers - " + responseHeaders); 47 | } 48 | 49 | private void addUser() { 50 | String url = baseUrl + "/user"; 51 | User user = new User(); 52 | user.setFirstName("Green"); 53 | user.setLastName("Learner"); 54 | user.setGender("M"); 55 | user.setAddress("Noida"); 56 | ResponseEntity responseEntity = restTemplate.postForEntity(url, user, String.class); 57 | 58 | HttpStatus statusCode = responseEntity.getStatusCode(); 59 | System.out.println("status code - " + statusCode); 60 | String userDetails = responseEntity.getBody(); 61 | System.out.println("response body - " + userDetails); 62 | HttpHeaders responseHeaders = responseEntity.getHeaders(); 63 | System.out.println("response Headers - " + responseHeaders); 64 | URI uri = restTemplate.postForLocation(url, user, String.class); 65 | System.out.println("uri - " + uri); 66 | } 67 | 68 | private void deleteUser(){ 69 | String url = baseUrl + "/user/20"; 70 | restTemplate.delete(url); 71 | System.out.println("User deleted"); 72 | } 73 | private void updateUser(){ 74 | String url = baseUrl + "/updateAddress/5/USA"; 75 | restTemplate.put(url, null); 76 | System.out.println("User updates"); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /userManagementClient/src/main/java/com/gl/userManagementClient/ForObjectMethodOfRestTemplateDemo.java: -------------------------------------------------------------------------------- 1 | package com.gl.userManagementClient; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.http.HttpHeaders; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.web.client.RestTemplate; 10 | 11 | import java.net.URI; 12 | import java.util.List; 13 | 14 | /** 15 | * @author - GreenLearner(https://www.youtube.com/channel/UCaH2MTg94hrJZTolW01a3ZA) 16 | */ 17 | public class ForObjectMethodOfRestTemplateDemo { 18 | private Logger logger = LoggerFactory.getLogger(ForObjectMethodOfRestTemplateDemo.class); 19 | private String baseUrl = "http://localhost:8083/springDataDemo/"; 20 | 21 | private RestTemplate restTemplate = new RestTemplate(); 22 | 23 | public void driverMethod(){ 24 | System.out.println("*********** forObject() method demo ***********"); 25 | getSingleObject(); 26 | getListObject(); 27 | addUser(); 28 | } 29 | private void getSingleObject() { 30 | String url = baseUrl + "/user/5"; 31 | String user = restTemplate.getForObject(url, String.class); 32 | logger.info("User - " + user); 33 | } 34 | 35 | private void getListObject() { 36 | String url = baseUrl + "/users"; 37 | List userDetails = restTemplate.getForObject(url, List.class); 38 | logger.info("response body - " + userDetails); 39 | 40 | } 41 | 42 | private void addUser() { 43 | String url = baseUrl + "/user"; 44 | User user = new User(); 45 | user.setFirstName("Green"); 46 | user.setLastName("Learner"); 47 | user.setGender("M"); 48 | user.setAddress("Noida"); 49 | String response = restTemplate.postForObject(url, user, String.class); 50 | 51 | logger.info("response - " + response); 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /userManagementClient/src/main/java/com/gl/userManagementClient/User.java: -------------------------------------------------------------------------------- 1 | package com.gl.userManagementClient; 2 | 3 | 4 | public class User { 5 | 6 | private Long id; 7 | 8 | private String firstName; 9 | 10 | private String lastName; 11 | 12 | private String gender; 13 | 14 | private String address; 15 | 16 | public Long getId() { 17 | return id; 18 | } 19 | 20 | public void setId(Long id) { 21 | this.id = id; 22 | } 23 | 24 | public String getFirstName() { 25 | return firstName; 26 | } 27 | 28 | public void setFirstName(String firstName) { 29 | 30 | this.firstName = firstName; 31 | } 32 | 33 | public String getAddress() { 34 | return address; 35 | } 36 | 37 | public void setAddress(String address) { 38 | this.address = address; 39 | } 40 | 41 | public String getLastName() { 42 | return lastName; 43 | } 44 | 45 | public void setLastName(String lastName) { 46 | this.lastName = lastName; 47 | } 48 | 49 | public String getGender() { 50 | return gender; 51 | } 52 | 53 | public void setGender(String gender) { 54 | this.gender = gender; 55 | } 56 | 57 | @Override 58 | public String toString() { 59 | return "User{" + 60 | "id=" + id + 61 | ", firstName='" + firstName + '\'' + 62 | ", lastName='" + lastName + '\'' + 63 | ", gender='" + gender + '\'' + 64 | ", address='" + address + '\'' + 65 | '}'; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /userManagementClient/src/main/java/com/gl/userManagementClient/UserManagementClient.java: -------------------------------------------------------------------------------- 1 | package com.gl.userManagementClient; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.http.*; 5 | import org.springframework.web.client.RestTemplate; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * Author - Green Learner(https://facebook.com/greenlearner)
11 | * Official youtube channel - https://www.youtube.com/channel/UCaH2MTg94hrJZTolW01a3ZA
12 | */ 13 | 14 | //@SpringBootApplication 15 | public class UserManagementClient { 16 | 17 | static RestTemplate restTemplate = new RestTemplate(); 18 | static String baseUrl = "http://localhost:8083/springDataDemo/"; 19 | 20 | 21 | @Autowired 22 | private static ForEntityMethodOfRestTemplateDemo forEntityMethodOfRestTemplateDemo; 23 | 24 | public static void main(String[] args) { 25 | //SpringApplication.run(UserManagementClient.class, args); 26 | useExchangeMethodsOfRestTemplate(); 27 | 28 | ForEntityMethodOfRestTemplateDemo forEntityMethodOfRestTemplateDemo = new ForEntityMethodOfRestTemplateDemo(); 29 | forEntityMethodOfRestTemplateDemo.driverMethod(); 30 | ForObjectMethodOfRestTemplateDemo forObjectMethodOfRestTemplateDemo = new ForObjectMethodOfRestTemplateDemo(); 31 | forObjectMethodOfRestTemplateDemo.driverMethod(); 32 | } 33 | 34 | private static void useExchangeMethodsOfRestTemplate() { 35 | 36 | HttpHeaders headers = new HttpHeaders(); 37 | headers.setContentType(MediaType.APPLICATION_JSON); 38 | 39 | HttpEntity requestEntity = new HttpEntity<>(headers); 40 | 41 | getSingleUserByExchangeMethod(requestEntity); 42 | getListUserByExchangeMethod(requestEntity); 43 | 44 | User sysUser = new User(); 45 | sysUser.setFirstName("Arvind"); 46 | sysUser.setLastName("Kuamr"); 47 | sysUser.setAddress("Noida"); 48 | sysUser.setGender("M"); 49 | //requestEntity = new HttpEntity<>(sysUser, headers); 50 | 51 | //addUserByExchangeMethod(requestEntity); 52 | 53 | //updateUserByExchangeMethod(requestEntity); 54 | 55 | //deleteUserByExchangeMethod(requestEntity); 56 | } 57 | 58 | private static void deleteUserByExchangeMethod(HttpEntity requestEntity) { 59 | ResponseEntity responseEntity = restTemplate.exchange(baseUrl + "user/21", 60 | HttpMethod.DELETE, 61 | requestEntity, 62 | String.class); 63 | HttpStatus statusCode = responseEntity.getStatusCode(); 64 | System.out.println("status code - " + statusCode); 65 | String userDetails = responseEntity.getBody(); 66 | System.out.println("response body - " + userDetails); 67 | HttpHeaders responseHeaders = responseEntity.getHeaders(); 68 | System.out.println("response Headers - " + responseHeaders); 69 | } 70 | 71 | private static void updateUserByExchangeMethod(HttpEntity requestEntity) { 72 | ResponseEntity responseEntity = restTemplate.exchange(baseUrl + "updateAddress/21/Delhi", 73 | HttpMethod.PUT, 74 | requestEntity, 75 | String.class); 76 | HttpStatus statusCode = responseEntity.getStatusCode(); 77 | System.out.println("status code - " + statusCode); 78 | String userDetails = responseEntity.getBody(); 79 | System.out.println("response body - " + userDetails); 80 | HttpHeaders responseHeaders = responseEntity.getHeaders(); 81 | System.out.println("response Headers - " + responseHeaders); 82 | } 83 | 84 | private static void addUserByExchangeMethod(HttpEntity requestEntity) { 85 | ResponseEntity responseEntity = restTemplate.exchange(baseUrl + "user", 86 | HttpMethod.POST, 87 | requestEntity, 88 | User.class); 89 | HttpStatus statusCode = responseEntity.getStatusCode(); 90 | System.out.println("status code - " + statusCode); 91 | User userDetails = responseEntity.getBody(); 92 | System.out.println("response body - " + userDetails); 93 | HttpHeaders responseHeaders = responseEntity.getHeaders(); 94 | System.out.println("response Headers - " + responseHeaders); 95 | } 96 | 97 | 98 | private static void getListUserByExchangeMethod(HttpEntity requestEntity) { 99 | ResponseEntity responseEntity = restTemplate.exchange(baseUrl + "users", 100 | HttpMethod.GET, 101 | requestEntity, 102 | List.class); 103 | HttpStatus statusCode = responseEntity.getStatusCode(); 104 | System.out.println("status code - " + statusCode); 105 | List user = responseEntity.getBody(); 106 | System.out.println("response body - " + user); 107 | HttpHeaders responseHeaders = responseEntity.getHeaders(); 108 | System.out.println("response Headers - " + responseHeaders); 109 | /* 110 | ResponseEntity responseUser = restTemplate.exchange(baseUrl + "user/5", 111 | HttpMethod.GET, 112 | requestEntity, 113 | User.class); 114 | User userBody = responseUser.getBody(); 115 | System.out.println("user object - " + userBody);*/ 116 | } 117 | 118 | private static void getSingleUserByExchangeMethod(HttpEntity requestEntity) { 119 | ResponseEntity responseEntity = restTemplate.exchange(baseUrl + "user/5", 120 | HttpMethod.GET, 121 | requestEntity, 122 | String.class); 123 | HttpStatus statusCode = responseEntity.getStatusCode(); 124 | System.out.println("status code - " + statusCode); 125 | String user = responseEntity.getBody(); 126 | System.out.println("response body - " + user); 127 | HttpHeaders responseHeaders = responseEntity.getHeaders(); 128 | System.out.println("response Headers - " + responseHeaders); 129 | 130 | ResponseEntity responseUser = restTemplate.exchange(baseUrl + "user/5", 131 | HttpMethod.GET, 132 | requestEntity, 133 | User.class); 134 | User userBody = responseUser.getBody(); 135 | System.out.println("user object - " + userBody); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /userManagementClient/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /userManagementClient/src/test/java/com/gl/userManagementClient/UserManagementClientApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.gl.userManagementClient; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class UserManagementClientApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------