Tuesday, 13 August 2019

RestWebService using Java Spring Boot

WebService sample for Sending Token / Some String data to the server



public class FcmToken {

private String content;



public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

}



public class FcmTokenReply {

private String content;

String registrationStatus;
int registrationStatusNumber;
public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public String getRegistrationStatus() {
return registrationStatus;
}

public void setRegistrationStatus(String registrationStatus) {
this.registrationStatus = registrationStatus;
}
public int getRegistrationNumber() {
return registrationStatusNumber;
}

public void setRegistrationStatusNumber(int registrationStatusNumber) {
this.registrationStatusNumber = registrationStatusNumber;
}

}



@RestController
public class FcmRegisterController {
@RequestMapping(method = RequestMethod.POST, value = "/register/token")
@ResponseBody
FcmTokenReply registerStudent(@RequestBody FcmToken fcmregdtoken) {
FcmTokenReply tokenreply = new FcmTokenReply();
//This operation we did so that we can get/fetch this using the get request
FCMGetToken.getInstance().add(fcmregdtoken);

         //We are setting the below value just to reply a message back to the caller

tokenreply.setRegistrationStatusNumber(200);
tokenreply.setRegistrationStatus("Successful");
tokenreply.setContent(fcmregdtoken.getContent());
return tokenreply;
}
}

We test this using POST Man by calling the following URL

http://localhost:8080/register/token and passing the following in the body selecting the content type as application xml/JSON


            "content":"dSSFOk:8OQmsO9W8cTxB3i6ymsjB9I5ngDzmstGsZv0lw6RbGf0tIMcD79nlEQG2hoWgxBqU5r-xK3_zTj7V38UF"
}

we get the response as successful


We will write another URL which will get the token which is registered using the POST URL



public class FCMGetToken {

private static FCMGetToken token = null;

private List<FcmToken> tokenRecords;
private String lastToken;

  private FCMGetToken(){
  tokenRecords = new ArrayList<FcmToken>();
    }
public static FCMGetToken getInstance() {
        if(token == null) {
        token = new FCMGetToken();
              return token;
            }
            else {
                return token;
            }
    }
public void add(FcmToken token) {
tokenRecords.add(token);
lastToken = token.getContent();
    }
public List<FcmToken> getTokenRecords() {
    return tokenRecords;
    }
public String getLastToken() {
    return lastToken;
    }
}



@RestController
public class FCMGetTokenController {


@RequestMapping(method = RequestMethod.GET, value = "/register/alltoken")
/* @ResponseBody
  public List<FcmToken> getAllStudents() {
  return FCMGetToken.getInstance().getTokenRecords();
  }*/
@ResponseBody
  public String getlastToken() {
  return FCMGetToken.getInstance().getLastToken();
  }
}

We can test this using the post man by the following URL

http://localhost:8080/register/alltoken


We Write one more webservice like /sendNotification to send the push notification to client app



@RestController
public class SendNotificationController {

public final static String AUTH_KEY_FCM = "key=FCM Console we can get this under cloud msging tab";
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";


@RequestMapping(method = RequestMethod.POST, value = "/sendNotification")
@ResponseBody
private String sendPOST() throws IOException {
String lastToken = FCMGetToken.getInstance().getLastToken();
System.out.println("Inside post "+lastToken);
URL obj = new URL(API_URL_FCM);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
// con.setRequestProperty("User-Agent", USER_AGENT);

// For POST only - START
con.setDoOutput(true);

con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json");

con.setRequestProperty("Authorization", AUTH_KEY_FCM);

String postJsonData = "{\r\n" +
"  \"notification\": \r\n" +
"  {\r\n" +
"    \"title\": \"Hello Client This is From Server\",\r\n" +
"    \"text\": \"Your Text\",\r\n" +
"    \"sound\": \"default\",\r\n" +
"    \"badge\": \"1\",\r\n" +
"    \r\n" +
"    \"color\": \"#990000\",\r\n" +
"      \r\n" +
"    \r\n" +
"  },\r\n" +
"  \"priority\" : \"high\",\r\n" +
"  \"registration_ids\" : \r\n" +
[\r\n" + "\""+
lastToken+ "\""+ "\r\n" +
"    ]\r\n" +
"}";



OutputStream os = con.getOutputStream();
os.write(postJsonData.getBytes());
os.flush();
os.close();
// For POST only - END
con.connect();
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);

if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
return "Success";
}

No comments:

Post a Comment

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...