2

My Post method in Angular

     private attachAuthorization(): RequestOptions {
     const headers = new Headers();
     headers.append('Content-Type', 'application/json');
headers.append('HttpHeaders.ACCEPT', 'MediaType.APPLICATION_JSON_VALUE');
headers.append('Content-Type', 'charset=UTF-8');
headers.append ('Authorization',sessionStorage.getItem('token'));
//console.log(localStorage.getItem('token'));
const options = new RequestOptions({
  headers: headers,
  responseType: ResponseContentType.Json,
});

return options;}


public post(url: string, requestData: any):any {
const options = this.attachAuthorization();
return this.http.post(url, JSON.stringify(requestData),options);


}

Json Array

[{"columnname":"symbol","filterby":"","values":"","time":"","datatype":"String"},{"columnname":"order_Receiving_Date","filterby":"","values":"","time":"","datatype":"DateRange"},{"columnname":"event_Type","filterby":"","values":"","time":"","datatype":"String"},{"columnname":"firm_ROE_ID","filterby":"","values":"","time":"","datatype":"int"},{"columnname":"rejected_ROE_ID","filterby":"","values":"","time":"","datatype":"int"}]


API Method

@RequestMapping(value = {"/Oats-Exception-summary"}, method = RequestMethod.POST)
 public ResponseEntity<List<OatsExceptionSummary>> OatsExceptionSummaryPost(
         @RequestBody JSONArray payload)throws SQLException,JSONException,Exception {
    System.out.println(payload);
    String FilterData="";
    /*JSONObject jsonObj=new JSONObject(payload);*/
    List<OatsExceptionSummary> Data =ISurveillanceService.getOatsExecptionSummary(FilterData);  
     if (Data.isEmpty()) {
            return new ResponseEntity<List<OatsExceptionSummary>>(HttpStatus.NO_CONTENT);
        } else {
            return new ResponseEntity<List<OatsExceptionSummary>>(Data, HttpStatus.OK);
        }
 }

**Error in API **

Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity> com.zcon.RSMS.SpringBoot_RSMS2.controller.SurveillanceController.OatsExceptionSummaryPost(org.json.JSONArray) throws java.sql.SQLException,org.json.JSONException,java.lang.Exception 2018-05-22 12:56:09.624 WARN 11855 --- [nio-8090-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity> com.zcon.RSMS.SpringBoot_RSMS2.controller.SurveillanceController.OatsExceptionSummaryPost(org.json.JSONArray) throws java.sql.SQLException,org.json.JSONException,java.lang.Exception

2
  • What do you see when you do System.out.println(payload);? Commented May 22, 2018 at 9:44
  • when I was passed through postman it printed but not work when send json array through Angular post method..so what I do now ? Commented May 22, 2018 at 11:01

3 Answers 3

2

Solved ..The problem is I have send empty Array reauestData[ ] but now I have changed array to json object

{

"data": [

{"columnname":"symbol","filterby":"","values":"","time":"","datatype":"String"},{"columnname":"order_Receiving_Date","filterby":"","values":"","time":"","datatype":"DateRange"},{"columnname":"event_Type","filterby":"","values":"","time":"","datatype":"String"},{"columnname":"firm_ROE_ID","filterby":"","values":"","time":"","datatype":"int"},{"columnname":"rejected_ROE_ID","filterby":"","values":"","time":"","datatype":"int"}

]

}


Post Method

component.ts

prepareData() {


console.log("this.FilterData"+JSON.stringify(this.FilterData)); 
  this.loading = true;
   this.SharedHttpClientService.post(
    this.UrlsService.setAPIURl(
      APIURL.Surveillance_OatsException_Summary),
      this.FilterData)
    .map((response: Response) => {
      this.isLoadingResults = false;
      this.isRateLimitReached = false;
      return response.json();
    })
    .subscribe(Element => {
      this.dataset=Element;
    },
      (err: HttpErrorResponse) => {
        this.isLoadingResults = false;
        this.isRateLimitReached = true;
    });
    this.loading = false;


}

service.ts

 private attachAuthorization(): RequestOptions {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
//headers.append('HttpHeaders.ACCEPT', 'MediaType.APPLICATION_JSON_VALUE');
headers.append ('Authorization',sessionStorage.getItem('token'));
//console.log(localStorage.getItem('token'));

const options = new RequestOptions({
  headers: headers,
  responseType: ResponseContentType.Json,

});

return options;
  }



public post(url: string, requestData: any):Observable<any>{
const options = this.attachAuthorization();
//console.log(localStorage.getItem('token'));
let Data={"data":requestData}
console.log("Data "+JSON.stringify(Data)); 
return this.http.post(url,JSON.stringify(Data),options);                                                                                                        


 }

API controller Function

   @RequestMapping(value = {"/Oats-Exception-summary/"}, method = RequestMethod.POST)
     public ResponseEntity<List<OatsExceptionSummary>> OatsExceptionSummaryPost(
             @RequestBody Map payload)throws SQLException,JSONException,Exception {
        JSONObject root = new JSONObject( payload);
        JSONArray dataArray = root.getJSONArray("data");
        for (int t=0; t<dataArray.length(); t++) {
            JSONObject JObject = dataArray.getJSONObject(t);
            System.out.println(JObject.getString("columnname"));
        }

        String FilterData="";
        //JSONObject jsonObj=new JSONObject(payload);
        List<OatsExceptionSummary> Data =ISurveillanceService.getOatsExecptionSummary(FilterData);  
         if (Data.isEmpty()) {
                return new ResponseEntity<List<OatsExceptionSummary>>(HttpStatus.NO_CONTENT);
            } else {
                return new ResponseEntity<List<OatsExceptionSummary>>(Data, HttpStatus.OK);
            }
     }
Sign up to request clarification or add additional context in comments.

Comments

0
//fist convert your json array into typescript

  //  than assin to any variable like
   documents: [{
           columnname: string;
           filterby: string;
           values: string;
           time: string;
           datatype: string;
        }];
 //than pass to in service like below
this.profileService.saveProfile(this.documents)
            .subscribe(response => { });
   //than use in your http post service like below example
 saveProfile(formData): Observable<any> {

                    return this.http.post(this.requestUrl, formData)
                      .map((res: Response) => {return res.json()})
                      .catch(this.handleError);
    }

Comments

0

You're stringifying the post body while your API expects a JSON array. Just remove the JSON.stringify and try again.

return this.http.post(url, requestData, options);

2 Comments

can you do console.log(requestData) and let me know the result
requestData [object Object],[object Object],[object Object],[object Object],[object Object]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.