Robospice upload file with SpringAndroidSpiceRequest - android

I am working with robospice. Now I want to upload file.
I used SpringAndroidSpiceService and write my own request like this :
public class UploadFileRequest extends SpringAndroidSpiceRequest<String>{
private static final String TAG = "UploadFileRequest";
private UploadRequestModel requestModel;
private String link;
public UploadFileRequest(UploadRequestModel model, String link) {
super(String.class);
requestModel = model;
this.link = link;
}
#Override
public String loadDataFromNetwork() throws Exception {
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("file1", new FileSystemResource(requestModel.getFile1()));
parts.add("file2", new FileSystemResource(requestModel.getFile1()));
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, Object>> request =
new HttpEntity<MultiValueMap<String, Object>>(parts, headers);
return getRestTemplate().postForObject(link, request, String.class);
}
}
I can send the files now. But I faced a problem.
After the files have sent. My files on disk are almost deleted. It's size is zero.
Do you know why ? and how can I resolve it ?
Thank you very much for any help.

I am on of the authors of RS. The problem you face is not related to RS directly but to Spring Android. I suggest you write to their forum to get an answer. Sorry, but we can't tell you more.
Stéphane

this.message.setApi_key(ConfigurationBean.getTab_id());
this.message.setApi_password(ConfigurationBean.getTab_assword());
this.message.setNursery_id(ConfigurationBean.getNursery_id());
url=ConfigurationBean.getNursery_url()+"/api/v1/installation.php";
try {
list=service.getConfiguration(admin, pass);
} catch (Exception e) {
Log.e("request", ""+e.getMessage());
}
// Add the Jackson and String message converters
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
// Make the HTTP POST request, marshaling the request to JSON, and the response to a String
String response = restTemplate.postForObject(url, message, String.class);
return response;
this is my code,
before i was getting the same problem ,not its working fine u can try this message enter code hereconverter which will help

Related

How to get token returned in response body (of authentication web service) using RestTemplate?

im using RestTemplate to call the authenticate web service and POST username and password,i need in return to get the token from response body but i can't find a clear way to do it..Here is my code
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Content-Type","application/json");
requestHeaders.add("Accept", "application/json");
requestHeaders.add("Authorization", auth_token);
final String url = "http://192.168.1.3:18080/api/authenticate";
RestTemplate restTemplate=new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("password",password);
map.add("username",username);
HttpEntity<MultiValueMap<String, String>> entity= new HttpEntity<MultiValueMap<String, String>>(map, requestHeaders);
String response = restTemplate.postForObject(url,entity,String.class);
return response;
and this is the response body that i need to get the token from it:web service response body
You're pretty much there, at the moment your code gets the whole JSON response as a string:
return restTemplate.postForObject(url,entity,String.class);
// {"id_token": "blahblahblah"}
Instead you can either transform to a Map and take the correct value:
Map<String, Object> response3 = restTemplate.postForObject(url, entity, Map.class);
return response3.get("id_token")
// blahblahblah
or create a class:
public class AuthResponse {
#JsonProperty( "id_token" )
private String idToken;
public String getIdToken() {
return idToken;
}
public void setIdToken(String idToken) {
this.idToken = idToken;
}
}
and transform that:
AuthResponse response4 = restTemplate.postForObject(url, entity, AuthResponse.class);
return response4.getIdToken();
// blahblahblah

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.

Send JSON in Post with robospice google http client

I have a problem with creating post requests and send json with Robospice google http java client. My problem is, that the server receives an empty request data. (Nothing in postData)
#Override
public AjaxResult loadDataFromNetwork() throws Exception {
JsonHttpContent jsonHttpContent = new JsonHttpContent(new JacksonFactory(), jsonObject);
//ByteArrayContent.fromString("application/json", jsonObject.toString())
HttpRequest request = getHttpRequestFactory().buildPostRequest(
new GenericUrl(baseUrl),
jsonHttpContent);
request.getHeaders().setContentType("application/json");
request.setParser(new JacksonFactory().createJsonObjectParser());
request.setContent(jsonHttpContent);
HttpResponse httpResponse = request.execute();
AjaxResult result = httpResponse.parseAs(getResultType());
return result;
}
Thanks in advance!
You can do something like this :
public class SignIn_Request extends GoogleHttpClientSpiceRequest<Login> {
private String apiUrl;
private JSONObject mJsonObject;
public SignIn_Request(JSONObject mJsonObject) {
super(Login.class);
this.apiUrl = AppConstants.GLOBAL_API_BASE_ADDRESS + AppConstants.API_SIGN_IN;
this.mJsonObject = mJsonObject;
}
#Override
public Login loadDataFromNetwork() throws IOException {
Ln.d("Call web service " + apiUrl);
HttpRequest request = getHttpRequestFactory()//
.buildPostRequest(new GenericUrl(apiUrl), ByteArrayContent.fromString("application/json", mJsonObject.toString()));
request.setParser(new JacksonFactory().createJsonObjectParser());
return request.execute().parseAs(getResultType());
}
}
Convert your JSON into byte array and include it in your post request.
I've been hunting around for a similar solution myself and I found a decent explanation of how Google want you to format the content.
I made POJO class and just added some getters and setters and used that for the data and it seemed to work for me.
google-http-java-client json update existing object

how to get the data into my Bean class with the help of RestTemplate object?

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.

Calling Rest webservice in Android

I have Java web application server [ acts like server ].
In Android application, using httppost i have calling the restwebserive server.
My calling is hit the webservice with the response code 200.
Now i want to pass the java class object as like parameter.
sample java class:
public Class Sample{
public String Username;
public String getUsername()
{
return Username;
}
public void setUsername(String user){
this.Username = user;
}}
Used code :[ Is not passing my class object to server ]
Sample sam = new Sample();
sam.setUsername("Test");
JSONObject json = new JSONObject();
json.put("Sample", sam);
StringEntity se = new StringEntity(json.toString());
Httppostrequest.setEntity(se);
when i debugging the server the sample object parameter input is empty.[Not passed properly]
How to pass the class object via http post in android?
Please help me on this.
Thanks in advance,
Kums
if you use apache library you can do it one line
JSONSerializer.toJSON(sam);
otherwise i think you have to send it as
Sample sam = new Sample();
sam.setUsername("Test");
JSONObject json = new JSONObject();
json.put("sample", sam.getUserName());
StringEntity se = new StringEntity(json.toString());
Httppostrequest.setEntity(se);
Here is a code snippet
public void callWebService(String q){
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(URL + q);
request.addHeader("deviceId", deviceId);
ResponseHandler<string> handler = new BasicResponseHandler();
try {
result = httpclient.execute(request, handler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
Log.i(tag, result);
} // end callWebService()
}
Use this method to call your webservice
I have built a library for doing async requests, you can send parameter requests as www.somedomain.com/action?param1="somevalue" etc.. and also there is the option to use string body.
https://github.com/darko1002001/android-rest-client
Check it out, it might be helpful.

Categories

Resources