HTTP Status 500 - org.springframework.web.client.HttpClientErrorException: 404 / - rest

I am using RestTemplate, but when i call postFor function i get following exception, Below are the code for showing detail:
Controller
#Controller
#RequestMapping("/data")
public class DataController {
#RequestMapping(value = "/{id}", method = RequestMethod.POST)
public ResponseEntity<ManagementResource> postData(#PathVariable("id") String id,#RequestBody Data1 data) {
RSResponse<Data1> response = new RSResponse<Data1>();
response.setStatus(RSResponse.Status.SUCCESS);
response.setData(data);
return new ResponseEntity<ManagementResource>(HttpStatus.CREATED);
}
}
client code:
RestTemplate rt = new RestTemplate();
Data1 d = new Data1();
d.setEmp_id(1);
d.setEmp_name("abc");
d.setEmp_salary(10000);
Map<String, String> vars = new HashMap<String, String>();
vars.put("id", "JS01");
String url = "http://localhost:8090/JSFFaceletsTutorial/data/{id}";
ResponseEntity<Data1> response = rt.postForEntity(url,d,Data1.class,vars);
Data1 data = response.getBody();
please tell if anyone knows it.
Thanks

Does your service need headers? If so, you can pass like this,
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("Accept", "application/json");
HttpEntity<Data1> request = new HttpEntity<Data1>(d, headers);
ResponseEntity<Data1> response = rt.postForEntity(url,request,Data1.class,vars);
Data1 data = response.getBody();

Related

Spring REST Endpoint Returning String instead of JSON

The following endpoint returns a username as a string.
How would I structure it to return a json object that contains a key with that string as its value (e.g., {"user":"joeuser"}?
#GetMapping(value = "/getUser", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getUser() {
HttpHeaders responseHeaders = new HttpHeaders();
CustomUserAuthentication authentication = (CustomUserAuthentication) SecurityContextHolder.getContext().getAuthentication();
return ResponseEntity.ok().headers(responseHeaders).body(String.valueOf(authentication.getPrincipal()));
}
Using some Json library (like gson), build the Json object and return it in the body instead of the String. Make sure response content-type is application/json
You can also manually build the String that looks like Json but content to must be as above.
Spring can do what you want, but you need to return something that Spring needs to marshal into JSON. From my previous answer: https://stackoverflow.com/a/30563674/48229
#RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
#ResponseBody
public Map<String, Object> bar() {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("test", "jsonRestExample");
return map;
}

How to make a POST request with multiple headers and a raw text body in Spring Boot REST?

The body is in raw text format and the request is a POST method. I am using this code.
#RequestMapping(value = "/run", method = RequestMethod.POST)
ResponseEntity<String> runReport(){
RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl = "requestURL";
String auth = "username:password";
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(Charset.forName("US-ASCII")) );
String authHeader = "Basic " + new String( encodedAuth );
// Defining the Headers
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("Authorization", authHeader);
headers.add("Content-Type", "multipart/form-data; boundary=\"Boundary_1_1153447573_1465550731355\"");
headers.add("Accept", "multipart/form-data");
// Defining the Body
String outputFormatType = "pdf";
String body = "--Boundary_1_1153447573_1465550731355\n"
+"Content-Type: application/json\n"
+"Content-Disposition: form-data;" + " "+"name=\"ReportRequest\"\n\n"
+"{\"byPassCache\":true,\"flattenXML\":false,\"attributeFormat\":"+ "\""+outputFormatType+"\"" +"}\n"
+"--Boundary_1_1153447573_1465550731355--";
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("username", "password"));
ResponseEntity<String> result = restTemplate.exchange(fooResourceUrl, HttpMethod.POST, entity, String.class);
return result;
}
It was solved by removing the following line:
restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("username", "password"));
As it was already being added in header. And added the body as a parameter to the HttpEntity constructor:
HttpEntity<String> entity = new HttpEntity<>(body, headers);

Unable to access REST API’s in Camunda

In our project , we are trying to use camunda BPMN. using camunda standalone distro and deployed and running in Tomcat.
login as a admin user and able to access cockpit and task lists.But,when we try access the APIs using a Java client . we are getting an unauthorized (401) error. Though we are sending JSESSIONID as a “Cookie”
Tried both DefaultHttpClient and HttpURLConnection - It didn’t work out
Note : JSESSIONID is retrieved by calling the login api with admin username and password.
Help me to solve the issue
Attached below is the java client code
public static void main(String[] args) {
CamundaBMPNClient bpmnClient = new CamundaBMPNClient();
Map<Integer, String> cookieHeader = bpmnClient.getCookieHeader();
bpmnClient.getListofTasks(cookieHeader);
}
public Map<Integer, String> getCookieHeader() {
String jSessionID = null;
Map<Integer, String> headerValues = new HashMap<Integer, String>();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(
"http://localhost:8090/camunda-webapp-tomcat-standalone-7.2.0/"
+ "api/admin/auth/user/default/login/cockpit");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.addHeader("Accept", "application/json");
String jsonString = new Gson()
.toJson("username=admin&password=admin#123");
StringEntity params;
try {
params = new StringEntity(jsonString);
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
Header[] cookieheader = response.getHeaders("Set-Cookie");
for (Header s : cookieheader) {
// Do your stuff here
System.out.println(s.getValue());
String[] str = s.getValue().split(";");
int i = 1;
for (String s1 : str) {
headerValues.put(i, s1.trim());
i++;
}
}
System.out.println("jSessionID::" + jSessionID);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return headerValues;
}
public void getListofTasks(Map<Integer, String> cookieHeader) {
int id = 0;
// DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(
"http://localhost:8090/camunda-webapp-tomcat-standalone-7.2.0/api/engine/engine/default/task");
request.addHeader("Content-type", "application/json");
String[] arrJSessionID = cookieHeader.get(1).split("=");
System.out.println("" + arrJSessionID[1]);
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID=",
arrJSessionID[1]);
cookie.setDomain("http://localhost:8090");
cookie.setPath("/camunda-webapp-tomcat-standalone-7.2.0/");
// cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
cookieStore.addCookie(cookie);
// httpclient.setCookieStore(cookieStore);
HttpClient httpclient = HttpClientBuilder.create()
.setDefaultCookieStore(cookieStore).build();
String jsonString = new Gson().toJson("{}");
StringEntity jsonStr;
try {
jsonStr = new StringEntity(jsonString);
request.setEntity(jsonStr);
HttpResponse response = httpclient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
Header[] header = response.getHeaders("Set-Cookie");
for (Header h : header) {
System.out.println(h.getValue());
}
System.out.println("statusCode::" + statusCode);
} catch (Exception e) {
e.printStackTrace();
}
}

Issue when getting response from Apache HttpClient

I'm trying to work with the response body of a HTTP POST action. I'm implementing the following method:
public class post2 {
public final static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
List<NameValuePair> formparams = new ArrayList <NameValuePair>();
formparams.add(new BasicNameValuePair("login_id", myID));
formparams.add(new BasicNameValuePair("api_key", myKey));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
HttpPost httppost = new HttpPost(myURL);
httppost.setEntity(entity);
CloseableHttpResponse response2 = httpclient.execute(httppost);
try {
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
EntityUtils.consume(entity2);
String responseBody = EntityUtils.toString(entity2);
System.out.println("finalResult"+responseBody.toString());
}
finally {
httpclient.close();
}
}
}
I'm just receiving a "HTTP/1.1 200 OK", followed by:
Exception in thread "main" java.lang.ClassCastException: org.apache.http.impl.execchain.HttpResponseProxy cannot be cast to org.apache.http.HttpEntity
at post2.main(post2.java:62)
How should I recover the body information from the WebService?
Thanks,
Leo
Had to move EntityUtils.consume(entity2); to the end of the block:
public final static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
List<NameValuePair> formparams = new ArrayList <NameValuePair>();
formparams.add(new BasicNameValuePair("login_id", myID));
formparams.add(new BasicNameValuePair("api_key", myKey));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
HttpPost httppost = new HttpPost(myURL);
httppost.setEntity(entity);
CloseableHttpResponse response2 = httpclient.execute(httppost);
try{
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
String responseBody = EntityUtils.toString(entity2);
System.out.println("finalResult"+responseBody.toString());
EntityUtils.consume(entity2);
}
finally {
httpclient.close();
}
}

Jersey client. MultivaluedMap goes empty

My RESTful client has this method:
public void testGetCateogrywiseData() {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
client.addFilter(new LoggingFilter(System.out));
WebResource service = client
.resource("http://localhost:8080/MyApp/rest/publicdata");
#SuppressWarnings("rawtypes")
MultivaluedMap queryParams = new MultivaluedMapImpl();
queryParams.add("latitude", "18.522387");
queryParams.add("longitude", "73.878437");
queryParams.add("categoryID", "2");
service.queryParams(queryParams);
ClientResponse response = service.get(ClientResponse.class);
System.out.println(response.getStatus());
System.out.println("Form response " + response.getEntity(String.class));
}
On the server side the method looks like this:
#Path("publicdata")
#GET
#Produces(MediaType.TEXT_HTML)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String getPublicData() throws JSONException {
MultivaluedMap<String, String> valueMap = uriInfo.getQueryParameters();
Long latString = Long.parseLong(valueMap.getFirst("latitude"));
Long lonString = Long.parseLong(valueMap.getFirst("longitude"));
Long categoryId = Long.parseLong(valueMap.getFirst("categoryID"));
// Do necessary stuff and return json string
return null;
}
My problem is the valueMap at the server end is always empty. It never gets the three parameters that I have sent from the client code. What am I missing?
The problem happens on this line:
service.queryParams(queryParams);
It successfully adds the query params, but it does not change the original service, it returns a new one to you. To make it work you need to change to this:
service = service.queryParams(queryParams);