SpringFrameWork: 500 Internal Server Error - android

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

Related

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.

Spring-android RestTemplate post fail

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?

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.

Send JSON data to compojure server from android

I'm trying to send some json data from Android to a clojure/compojure server
However I can't seem to able to properly send or receive the data, and I'm not quite sure if the problem lies with Android or compojure.
Here is the java code
String PATH = "http://localhost:8080/get_position";
DefaultHttpClient mClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(PATH);
HttpResponse response;
httpget.getParams().setParameter("measurements", measurements.toString());
response = mClient.execute(httpget);
HttpEntity entity = response.getEntity();
Where mesurements is the JSON object.
And the main compojure code for handling the routing
(defroutes main-routes
(POST "/get_position" {params :params}
(emit-json (find-location (:results (read-json (:measurements params))))))
(route/not-found "Page not found"))
The request is properly received, but I get an error that params is nil
java.lang.IllegalArgumentException: No implementation of method: :read-json-from of protocol: #'clojure.data.json/Read-JSON-From found for class: nil
Does anyone see a problem with this code or knows the correct way to do this?
The params map has strings as keys, I believe, not keywords.
I recommend using ring-json-params.

sending json object to HTTP server in android

I am sending a JSON object to a HTTP Server by using the following code.
The main thing is that I have to send Boolean values also.
public void getServerData() throws JSONException, ClientProtocolException, IOException {
ArrayList<String> stringData = new ArrayList<String>();
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://consulting.for-the.biz/TicketMasterDev/TicketService.svc/SaveCustomer");
JSONObject json = new JSONObject();
json.put("AlertEmail",true);
json.put("APIKey","abc123456789");
json.put("Id",0);
json.put("Phone",number.getText().toString());
json.put("Name",name.getText().toString());
json.put("Email",email.getText().toString());
json.put("AlertPhone",false);
postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
String response = httpClient.execute(postMethod,resonseHandler);
Log.e("response :", response);
}
but its showing the exception in the line
String response = httpClient.execute(postMethod,resonseHandler);
as
org.apache.http.client.HttpResponseException: Bad Request
can any one help me.
The Bad Request is the server saying that it doesn't like something in your POST.
The only obvious problem that I can see is that you're not telling the server that you're sending it JSON, so you may need to set a Content-Type header to indicate that the body is application/json:
postMethod.setHeader( "Content-Type", "application/json" );
If that doesn't work, you may need to look at the server logs to see why it doesn't like your POST.
If you don't have direct access to the server logs, then you need to liaise with the owner of the server to try and debug things. It could be that the format of your JSON is slightly wrong, there's a required field missing, or some other such problem.
If you can't get access use to the owner of the server, the you could try using a packet sniffer, such as WireShark, to capture packets both from your app, and from a successful POST and compare the two to try and work out what is different. This can be a little bit like finding a needle in a haystack though, particularly for large bodies.
If you can't get an example of a successful POST, then you're pretty well stuffed, as you have no point of reference.
This may be non-technical, but
String response = httpClient.execute(postMethod,-->resonseHandler);
There is a spelling mistake in variable name here, use responseHandler(defined above)

Categories

Resources