Client Device Identification in REST API using Java & Spring Boot
Technology
To identify the request origin we use the request header. Request Header stores additional metadata of request. In the header “user-agent” store device and application information.
Code:
1.Controller:
@RestController
public class DeviceDetectController {
private DeviceDetectService deviceDetectService;
public DeviceDetectController(DeviceDetectService deviceDetectService) {
this.deviceDetectService = deviceDetectService;
}
@GetMapping("/test")
public String request(@RequestHeader(value = "User-Agent") String userAgent){
return deviceDetectService.detect(userAgent);
}
}
2.Service:
@Service
public class DeviceDetectService {
Logger logger= LoggerFactory.getLogger(DeviceDetectService.class);
public String detect(String device){
device=String.valueOf(device);
System.out.println(device);
if(device.contains("Mobile")){
logger.info("Mobile");
return "Mobile";
} else if (device.contains("Windows")) {
logger.info("Windows");
return "windows";
}else if (device.contains("Mac")) {
logger.info("Mac");
return "Mac";
}
logger.info("Failed");
return "Failed";
}
}
Test result:
MAC =>
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36
MOBILE =>
Mozilla/5.0 (Linux; Android 12; RMX2170) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Mobile Safari/537.36
WINDOWS =>
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36
Mobile Desktop =>
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36
Flutter basic app =>
It shows the dart version.
ex- Dart/2.15.0 (dart: io)
<= (This is search data. It not test yet.) Default
Note:
To get the actual information of the device and identify which of our applications use the API
we have to edit the user-agent of the request header and add our application name with the version in it.
Categories
Recent Posts
- Client Device Identification in REST API using Java & Spring Boot
- Extract Meta Data and Compress RAW Images using Python
- Twilio SMS API Integration with Java & Spring Boot for Sending OTP
- Razorpay Payment Gateway Implementation for Merchants using Java & Spring Boot
- Pagination using Spring Boot & Spring Data JPA