Spring-android RestTemplate post fail - android

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?

Related

SpringFrameWork: 500 Internal Server Error

I am working in an Android app that gets the data from the Server through REST services.
Now I have to make a POST on the REST service with a Body. But i am having problem doing that. I am using SPRINGFRAMEWORK to communicate with the REST service. But I am having this error:
org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error
Here is my code for posting:
org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error
final String url = "http://mywebsite.com/login";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Credentials> entity = new HttpEntity<>(credentials ,requestHeaders);
//the object "CREDENTIALS" has the valus that should be sent as BODY in the REST Service
For posting i used two ways, but none of them worked:
ResponseEntity<AllData> response = restTemplate.exchange(url, HttpMethod.POST, entity, AllData.class);
or
ResponseEntity<AllData> response = restTemplate.postForEntity(url, entity, AllData.class );
Any idea why I am having this problem??
P.s. I checked many of the questions that were like me but in none of them I could find a answer. I am trying since some days but can't figure out what the problem is :#
I was exactly the same problem, and I managed to solve it. Bringing to your example I needed to change the Credentials entity type to the same ResponseEntity type. Would be like this :
final String url = "http://mywebsite.com/login";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
AllData allData = new AllData();
HttpEntity<AllData> entity = new HttpEntity<>(allData, requestHeaders);
ResponseEntity<AllData> response = restTemplate.exchange(url, HttpMethod.POST, entity, AllData.class);
Since you say it's working from postman and other I'm guessing it's an encoding or headers issue.
I guess the easiest way to find the problem will be to use a proxy like fiddler and check the compare the headers and data sent from the Android device to those sent by postman or another tool

Querying an api with android spring?

I'm pretty new to both android and RESTful resources (been learning Rails and RoboSpice). I have a rails api setup correctly and for starters I'd like to pass a user name and password to the api and get a user model object back. I've been looking at the docs and examples and it's been pretty confusing. I was hoping someone could give me a quick example or point me at a good tutorial. Just for a test case, could someone walk me through this snippet and how could I adjust it to query?:
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAcceptEncoding(ContentCodingType.IDENTITY);
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
// Make the HTTP GET request, marshaling the response to a String
ResponseEntity<User> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, User.class);
Also, specifically what do the headers do? and how do I set up a class to recieve the response? i.e. User.class to receive a User model. That part confuses me the most >.< It seems disorganized..
thanks for any help!
This is a very simple example:
private static final String TAG = "HTTP CLIENT: ";
public String login(String User,String Pass){
Log.d(TAG, "Login Attempt!!!");
String result = "Empty!!!";
String url = "http://somehost.somedomain.com:8080/login?email="+User+"&password="+Pass;
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
try {
result = restTemplate.getForObject(url, String.class, "");
}catch (Exception e){
result = e.getMessage();
Log.d(TAG, "Exception Message: "+e.getMessage()+" "+e.getCause());
}
Log.d(TAG, "Token: "+result);
return result;
}
in regards to the Headers they are use to set the type of content that you will handle, for example JSON or XML data.

Robospice loadDataFromNetwork() not working

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())

Can't get character encoding to work from android client with resttemplate and json

Ok, so ive tried everything but asking at stackoverflow...
I'm trying to perform a REST call with some http params from an Android using httpclient and resttemplate to a server-side Spring controller. All my Swedish chars end up on the server as '\u001A'...
setting up httpclient and resttemplate code:
HttpClient httpClient = new HttpClient();
Credentials defaultcreds = new UsernamePasswordCredentials(msisdn, password);
httpClient.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), defaultcreds);
//httpClient.getParams().setContentCharset(prefs.());
httpClient.getParams().setCredentialCharset(prefs.getCredentialsEncoding());
CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
// Add message converters
List<HttpMessageConverter<?>> mc = restTemplate.getMessageConverters();
MappingJacksonHttpMessageConverter json = new MappingJacksonHttpMessageConverter();
List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
json.setSupportedMediaTypes(supportedMediaTypes);
mc.add(json);
restTemplate.setMessageConverters(mc);
return restTemplate;
I then prepare a httpentity with my parameter:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("myparam", "" + "å");
HttpEntity<String> entity = new HttpEntity<String>(headers);
I finally make the rest call:
ResponseEntity<UserStatusTO> response = rest.exchange(url, HttpMethod.GET, entity,
MyResponseClass.class);
On the server, i have a jackson deserializer and my spring controller method looks like:
#RequestMapping(method = RequestMethod.GET, value = "/event/out", headers = "Accept=application/json", produces = {"application/xml;charset=UTF-8", "application/json;charset=UTF-8"})
public
#ResponseBody
UserStatusTO out(Authentication auth, #RequestHeader(value="myparam", required = false) String myparam) {
All the special chars end up as \u001a ! I've tried tons of stuff, re-encoding the strings manually client AND server side, none worked. I've tried fiddling with the
httpClient.getParams().setContentCharset();
httpClient.getParams().setUriCharset();
None worked as far as i could tell.
I'm out of ideas! If anybody has any input, i'd be much obliged. Thanks!
I had a similar issue and I fixed it by setting the proper content-type AND character set manually instead of using MediaType.APPLICATION_JSON:
HttpHeaders headers = new HttpHeaders();
Charset utf8 = Charset.forName("UTF-8");
MediaType mediaType = new MediaType("application", "json", utf8);
headers.setContentType(mediaType);
This sounds like an issue on the server side since the Apache HTTP client will gladly output Latin-1 characters in headers, as you can test with this simple test:
HttpGet get = new HttpGet("http://www.riksdagen.se");
get.addHeader("SwedishHeader", "Mona Sahlin är ett nötdjur");
ByteArrayOutputStream out = new ByteArrayOutputStream();
SessionOutputBufferImpl buffer = new SessionOutputBufferImpl(out, get.getParams());
HttpRequestWriter writer = new HttpRequestWriter(buffer, BasicLineFormatter.DEFAULT, get.getParams());
writer.write(get);
buffer.flush();
System.out.println(out.toString("ISO-8859-1"));
SessionOutputBufferImpl is a little hack to use the AbstractSessionOutputBuffer
class SessionOutputBufferImpl extends AbstractSessionOutputBuffer {
SessionOutputBufferImpl(OutputStream out, HttpParams params) {
init(out, 1024, params);
}
}
You should probably concentrate on your server backend - what are you using? If it's "fixed" - you should consider trying to format your header according to RFC 2407 - some servers support, others fail miserably.

Android POST JSON Array to Server

I am having problems trying to POST a JSON Array.
For my Android code, I pass the JSON Array into the server by doing:
interests = // JSONArray of JSONObjects
final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(PARAM_USERNAME, username));
params.add(new BasicNameValuePair(PARAM_INTERESTS, interests.toString()));
HttpEntity entity = new UrlEncodedFormEntity(params);
final HttpPost post = new HttpPost(UPDATE_INTERESTS_URI);
post.setEntity(entity);
// POST data to server
But when I read it from the server using:
$interests = $_POST["interests"];
echo $interets
It looks like [{\"a\":\"1\"},{\"b\":\"2\"}] instead of [{"a":"1"},{"b":"2"}]. The first one won't decode properly, and the second one works.
So why is it not working?
EDIT:
When I look at on Android before it posts, the JSONArray.toString() looks like [{"a":"1"},{"b":"2"}]
Don't know about android, but that looks like the magic quotes-feature of PHP is adding those slashes, if that's the case you could use this on server-side:
$interests = $_POST["interests"];
if (get_magic_quotes_gpc()) {
$interests = stripslashes($interests);
}
echo $interests;
do it in this way:
JSONObject paramInput = new JSONObject();
paramInput.put(PARAM_USERNAME, username);
paramInput.put(INTERESTS, interests.toString());
StringEntity entity = new StringEntity(paramInput.toString(), HTTP.UTF_8);
You can try to use:
StringEntity params = new StringEntity("your_Data");
instead of your UrlEncodedEntity.

Categories

Resources