ajinkya933

POST in REST API using ApacheHttpClient and Java

Discussion created by ajinkya933 on May 6, 2016
Latest reply on Jan 18, 2017 by Tobias Murray

I am using Java for Posting JSON payload to Canvas Rest Api using ApacheHttpClient

I am getting error:Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 422.

My code is:

 

try{

  httpClient = HttpClients.createDefault();
  httpPost = new HttpPost("https://canvas.instructure.com/api/v1/courses/10300000000000133/assignments/10300000000000860");

  List<NameValuePair> headers = new ArrayList<NameValuePair>(); //ArrayList to store header parameters
  List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); //ArrayList to store URL parameters
  urlParameters.add(new BasicNameValuePair("query","{\"id\":10300000000000860,\"description\":\"\",\"due_at\":\"2017-04-19T03:59:59Z\",\"unlock_at\":\"2016-04-13T04:00:00Z\",\"lock_at\":\"2016-04-22T03:59:00Z\",\"points_possible\":3,\"grading_type\":\"points\",\"assignment_group_id\":10300000000000297 \"}"));
  headers.add(new BasicNameValuePair("app-token", "1030~SAD..."));
  headers.add(new BasicNameValuePair("Accept", "application/json, text/javascript, */*; q=0.01"));
  headers.add(new BasicNameValuePair("X-Requested-With", "XMLHttpRequest"));

  for (NameValuePair h : headers)
  {
  httpPost.addHeader(h.getName(), h.getValue());
  }

  response = httpClient.execute(httpPost);

  if (response.getStatusLine().getStatusCode() != 200) {
  throw new RuntimeException("Failed : HTTP error code : "
  + response.getStatusLine().getStatusCode());
  }

  BufferedReader br = new BufferedReader(new InputStreamReader(
  (response.getEntity().getContent())));

  String output;
  System.out.println("Output from Server .... \n");
  while ((output = br.readLine()) != null) {
  System.out.println(output);
  }
  } catch (MalformedURLException e) {

  e.printStackTrace();

  } catch (IOException e) {

  e.printStackTrace();

  }

 

The  token seems to be working .How do I correct this error.

Outcomes