I am using spring android in robospice. I need to place headers with get request so i used exchange() method. The code has no error but does not fetch anything
public MList loadDataFromNetwork() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add(key,keyValue);
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<MList> response=getRestTemplate().exchange(url,HttpMethod.GET,entity,MList.class);
return getRestTemplate().exchange(url, HttpMethod.GET,new HttpEntity<Object> (headers),MList.class).getBody();
}
RestTemplate restTemplate=new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.add(key,keyValue);
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<Pojo> response=restTemplate.exchange(url,HttpMethod.GET,entity,Pojo.class);
return response.getBody();
It worked when I edited the code like this.
But I got a null pointer exception when used
RestTemplate restTemplate=getRestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter())
Related
Hi I want to take the HTTP status codes when something goes wrong with the network.
I use try catch but I can only take the message. How I can take only the codes.
Also something else. There is any event called automatically if something go wrong? canI can override it?
This is my code into asyncTask
protected HistoricalWeatherResponse doInBackground(String... params) {
HistoricalWeatherResponse response = new HistoricalWeatherResponse();
try {
HttpHeaders requestHeaders = new HttpHeaders();
List<MediaType> acceptableMedia = new ArrayList<MediaType>();
acceptableMedia.add(MediaType.APPLICATION_JSON);
requestHeaders.setAccept(acceptableMedia);
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
ResponseEntity<HistoricalWeatherResponse> responseEntity = restTemplate.exchange("http://api.openweathermap.org/data/2.5/history/city?q="+params[0]+"&cnt=2", HttpMethod.GET, requestEntity, HistoricalWeatherResponse.class);
response = responseEntity.getBody();
response.setSuccess(true);
} catch (Exception e) {
response.setError(e);
response.setSuccess(false);
Log.d("LEE",e.getMessage());
}
return response;
}
Thanks!
I am new to work with RestTemplates.In my application i am trying to send request by using post method as follows
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(new MediaType("application","json",Charset.forName("UTF-8")));
requestHeaders.add("username", "sai3");
requestHeaders.add("password", "x");
requestHeaders.add("device_id", device_id);
HttpEntity<String> requestEntity = new HttpEntity<String>(requestHeaders);
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
` restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
ResponseEntity<GetResponseBean> responseEntity1 = restTemplate.exchange(url, HttpMethod.POST, requestEntity, GetResponseBean.class);
obj = responseEntity1.getBody();
Log.v("GetDataResponse", "result message : "+obj);
For the above code i have used "spring-android-core-1.0.1.RELEASE.jar","spring-android-rest-template-1.0.1.RELEASE.jar" and "jackson-all-1.9.8.jar"
If I use ResponseEntity type is String then it is returning fine response but If I change ResponseEntity type GetResponseBean type then i am getting error as follow :
Caused by: org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [com.example.springsxmlposting.GetResponseBean] and content type [text/html]
GetResponseBean class as follows:
public class GetResponseBean {
String result = null;
String message = null;
public void setmResult(String result) {
this.result = result;
}
public String getmResult() {
return result;
}
public void setmMessage(String message) {
this.message = message;
}
public String getmMessage() {
return message;
}
}
How can i get the data into my bean class (GetResponseBean) please any body help me
I think the problem relies in your server. You're sending content-type: application/json but as you can see in your error, it states that the response you get is text/html and not application/json.
My guess is that the response you're getting back is an error html page that states that you don't have a request that returns application/json. You can try and use an external tool for sending the request to the server. Do a POST request with the same headers and I bet you'll get an HTML error page.
PROBLEM
I'm thinking of converting my existing http post method to spring-android but I failed.
JSONObject defaultJsonObject = new JSONObject();
defaultJsonObject.put("ln", "Kiat");
defaultJsonObject.put("CountryName", "Malaysia");
defaultJsonObject.put("CityName", "Kuala Lumpur");
This is my existing http post which is working and will form a post body as : [json={"ln":"Kiat","CountryName":"Malaysia","CityName":"Kuala Lumpur"}]
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", jsonObject.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
System.out.println("post param: " + postParams.toString());
post.setEntity(entity);
post.setHeader("Accept", "application/json");
but when I convert to Spring-android with RestTemplate it failed. Even I already managed to form the post body as [json={"ln":"Kiat","CountryName":"Malaysia","CityName":"Kuala Lumpur"}] I keep getting 500 Internal Server Error
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
List<NameValuePair> postParams1 = new ArrayList<NameValuePair>();
postParams1.add(new BasicNameValuePair("json", jsonObject.toString()));
HttpEntity<?> requestEntity = new HttpEntity<Object>(postParams1, requestHeaders);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity,String.class)
The post body format will be something like this
[json={"ln":"Kiat","CountryName":"Malaysia","CityName":"Kuala Lumpur"}]
(Answered in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
Problem solved. SOLUTION:
To use RestTemplate, if you not sure what converters you need then you have to set TRUE in constructor. RestTemplate restTemplate = new RestTemplate(true); With this, it will include all the standard converters. But it kinda like a waste because you have to include all unwanted converters.
For my case, after testing, I found out I need two converters to make my HTTP post success which are
restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
I do not know what we need combination of converters; maybe someone has a deeper explanation?
Jax-rs service return HTTP Status 405 - Method Not Allowed.
Service:
#GET
#Consumes(MediaType.TEXT_HTML)
#Produces(MediaType.APPLICATION_JSON)
#Path("login")
public User Login(#QueryParam("u") String username, #QueryParam("p") String password) {
return UserDAO.getInstance().getLogin(username,password)
}
Android:
public static Boolean Login(User user) {
String url = "http://myserver.com/AndroidServis/rest/login?u={u}&p={p}";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HashMap<String, String> params = new HashMap<String, String > ();
params.put("u", user.getUsername().toString());
params.put("p", user.getPassword().toString());
HttpEntity entity = new HttpEntity(headers);
restTemplate.getMessageConverters().add(new GsonHttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
HttpEntity < Korisnici > response = restTemplate.exchange(url, HttpMethod.GET, entity,User.class, params);
}
It doesn't make sense for the server to have a #Consumes annotation on the #GET method, as this is typically only used for PUT or POST requests where the client is sending some content to the server.
Can you remove this?
Then also remove this from the client code.
headers.setContentType(MediaType.APPLICATION_JSON);
and you may need to uncomment the line you have commented out:
headers.set("Accept", "application/json");
This tells the server what content type is expected in the response so must match what the #Produces of the service.
I am using spring android framework for retrieving json data via Http GET. I am getting following exception for the same :
- Could not read JSON: Can not deserialize instance of com.springandroidjsondemo.beans.LoginBean[] out of START_OBJECT token
The bean (LoginBean) is Following
package com.springandroidjsondemo.beans;
public class LoginBean {
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
The android code is following :
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the Jackson message converters
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
// Make the HTTP GET request, marshaling the response from JSON to an array of Events
ResponseEntity<LoginBean[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity,LoginBean[].class); // getting exception here
LoginBean[] loginBean = responseEntity.getBody();
String status = loginBean[0].getStatus();
The json response from the server is following :
{"emp-data":[{"status":"true"}]}
I am not sure if any annotations are required for Jackson Marshalling
Please suggest the solution
Thanks!
this is a Jackson deserialization issue. if you compare the JSON response with your LoginBean, the array of statuses is contained within the element "emp-data". However, your RestTemplate request is expecting JSON which looks like the following.
[{"status":"true"},{"status":"false"}]
You have a couple options. You can create a wrapper object around LoginBean. Or you can try annotating the LoginBean like the following:
#JsonRootName(value = "emp-data")
public class LoginBean {
...
}
In order for this to work, you probably need to configure the Jackson ObjactMapper.
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
MappingJackson2HttpMessageConverter jackson = new MappingJackson2HttpMessageConverter();
jackson.setObjectMapper(objectMapper);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(jackson);