Upload files from android to wcf - android

Well Ive looked for hours and hours after an answer but havent really found anything that I could use.
I want to be able to send/upload files (images, videos, documents, audio) to a webservice. I want to do this from an android device (version 2.2).
I need to be able to send this to a tailormade wcf for my needs, I need to send information with the file in order to verify the user who wants to upload.
Also worth mentioning is I use a restful wcf .net webservice which I prefer to continue to use if possible. Atleast I need to be able to use wcf .net as webservice for the communication.
All solutions Ive seen concentrate on the android part and never on the service part. I need both. :)

This blog post
http://reecon.wordpress.com/2010/04/25/uploading-files-to-http-server-using-post-android-sdk/
describes how you can upload files with HTTP POST - which you must use from Android if you want to upload files to a WCF service wired up with webHttpBinding.
Extra metadata can be sent as HTTP headers.
--larsw

Ion.with(getActivity())
.load(URL)
.setMultipartFile("upload", "image/jpeg", fileToUpload)
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception arg0, String result) {
hideProgressDialog();
if(result!=null){
CoreFragment.this.resultCallBack.returnResult(result.toString());
} else {
showErrorToast("Error");
}
}
});
and wcf is
public string upload(Stream stream)
{
MultipartParser parser = new MultipartParser(stream);
if (parser.Success)
{
try
{
string strServerpath = #"C:\IISWebsite\DOTNET\BGGTS\Files\AttendanceProof\" + parser.Filename;
File.WriteAllBytes(strServerpath, parser.FileContents);
}
catch (Exception ex)
{
return "Failed";
}
}
return "Success";
}

Related

Returning server data using Volley - Android

I have an Android application that makes some requests on the server and also for sending data via web service, using the Volley library.
The data sent by the application are received by an API, and when there is confirmation, the API returns a specific value.
My problem is that I'm not getting this specific return from the API. How do I get this return, not only the server response 200 return that is received by library default?
You need to override parseNetworkResponse(NetworkResponse response)
Exemple :
#Override
protected Response<Bitmap> parseNetworkResponse(NetworkResponse response) {
// Serialize all decode on a global lock to reduce concurrent heap usage.
try {
return doParse(response); //your parser function
} catch (OutOfMemoryError e) {
//..Catch
}
}
Take a look to the doc.
Hope it helps,

how to create Appoinment from Android MS CRM SDK?

i am creating appointment using below code give "500 Internal Server Error"
i added all fields check it
Appointment objappointment = Appointment.build()
.setSubject("Android sub")
.setDescription("dis from device")
.setRegardingObjectId(new EntityReference("account", UUID.fromString("0717b8e2-d00a-e611-8115-c4346bdd11d1")))
.setOwnerId(new EntityReference("systemuser", UUID.fromString("3edb272d-2da7-4c89-9350-2f4bd4e1762b")))
.setStateCode(new OptionSetValue(0))
.setNew_Latitude(23.7845)
.setNew_Longitude(73.6574)
.setNew_City("Surat")
.setActualStart(mDate.getTime())
.setActualEnd(mDate1.getTime())
.setNew_ZipPostalCode("380060")
.setNew_Street1("Street1")
.setNew_Street2("Street3")
.setNew_street3("Street3")
.setNew_StateProvince("Gujarayt")
.setNew_CountryRegion("India")
.setNew_Latitude(23.7845)
.setNew_Longitude(73.6574)
.setStatusCode(new OptionSetValue(0))
.setPriorityCode(new OptionSetValue(2));
try {
RestOrganizationServiceProxy restService = new RestOrganizationServiceProxy(mOrgService);
restService.Create(objappointment,new Callback<UUID>() {
#Override
public void success(UUID uuid, Response response) {
log("sucess", uuid.toString());
}
#Override
public void failure(RetrofitError error) {
displayError(error.toString());
log("error", error.toString());
}
});
}
catch(Exception ex) {
displayError(ex.getMessage());
log("msg",ex.toString());
}
another entity create successfully using above code just got error in "Appoinment"
Could you get more details of the exception? 500 could be any exception. At least you know the request hit the server and it's failing on the CRM server side. Maybe a plugin or similar is raising the exception.
I think you have to pass the objectid to whom the annotation will be linked to (Account, Contact, or whatever...)
Is that on-premise or online CRM? If OnPremise you could enable includeExceptionDetailInFaults property in the web.config to at least get more details of the exception....

How to receive file on Spring server send from a client using retrofit2

I am currently trying to upload a file from an android client using retrofit2 to a server using Spring Boot and its REST api.
CLIENT
I specifiy the upload method as described here: https://github.com/square/retrofit/issues/1063
public interface RetroRespondService {
#Multipart
#POST("/v1/answers")
public Call<ResponseDTO> sendPictures(#Part("file\"; filename=\"image.png")RequestBody image);
}
In another class the method to provide the actual image is declared:
(Now its just a test scenario. When image uploading is actually accomplished it will get more sophisticated.)
public void performAnswerRequest() {
try {
if (mRetrofit == null) {
mRetrofit = new Retrofit.Builder()
.baseUrl(DataHolder.getHostName())
.build();
}
//load test image
AssetManager manager = getAssets();
File file = new File(getFilesDir(), "image.png");
Utility.writeBytesToFile(new BufferedInputStream(manager.open("heart.png")), file);
RetroRespondService requestService = mRetrofit.create(RetroRespondService.class);
RequestBody image= RequestBody.create(MediaType.parse("multipart/form-data"), file);
Call<ResponseDTO> response = requestService.sendPictures(image);
response.enqueue(new AsyncAnswerResponse());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
SERVER
What I actually do not know is, how to properly get the image on the spring side.
#RequestMapping(value = API_VERSION + "/answers", method = RequestMethod.POST)
#ResponseBody
ResponseEntity<ResponseDTO> addAnswers(#RequestParam("file\"; filename=\"image.png") MultipartFile answers) throws DBEntryDoesNotExistException, EvaluationException, ParticipantException {
// In fact I have set a brake point here. Never entered the method yet, though
System.out.println("Yay!")
return null;
}
ERROR
Request: localhost:8080/v1/answers raised org.springframework.web.bind.MissingServletRequestParameterException:
Required MultipartFile parameter 'file"; filename="image.png' is not present
Since wireshark reports that in fact a request of size 1894 Bytes was send and this is the size of the image i want to upload I strongly believe the the data is actually transmitted but cannot be decoded from the server.
I have also seen this answers: How to config "CommonsMultipartResolver" in spring4 without xml to upload file
and subsequently implemented this class on the server side:
#Configuration
public class MultipartConfiguration {
#Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver resolver=new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
resolver.setMaxUploadSize(1048576);
return resolver;
}
}
If you have any pointers in how to solve this I would appreciate your answer tremendously :)
If there are any questions left unanswered feel free to ask away.
Btw.: Sending and receiving JSON encoded data works just fine in both directions.

How to retrieve details of single video from youtube using videoID through Data API v3.0 in Android?

My server sends the list of videoID to Android. Now, I want to show Title, Thumbnail and Number of Comments on these videos in List View. I have done this in web using GET request to https://www.googleapis.com/youtube/v3/videos?part=snippet&id={VIDEO_ID}&key={YOUR_API_KEY} but how to do this in Android? Is there any YouTube SDK to initialize YouTube object? How do I retrieve this information from YouTube using VideoID?
EDIT: I have found a way to this using YouTube Data API Client Library for Java but It is giving runtime error without any explanation.
Here is the code I used
/**
* Define a global instance of a Youtube object, which will be used
* to make YouTube Data API requests.
*/
private static YouTube youtube;
youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer(){
public void initialize(com.google.api.client.http.HttpRequest request) throws IOException {
}
}).setApplicationName("youtube-cmdline-search-sample").build();
// Call the YouTube Data API's videos.list method to retrieve videos.
VideoListResponse videoListResponse = youtube.videos().
list("snippet").setId(videoId).execute();
// Since the API request specified a unique video ID, the API
// response should return exactly one video. If the response does
// not contain a video, then the specified video ID was not found.
List<Video> videoList = videoListResponse.getItems();
if (videoList.isEmpty()) {
System.out.println("Can't find a video with ID: " + videoId);
return;
}
Video video = videoList.get(0)
// Print information from the API response.
}
YouTube provides (at least) two official libraries relevant to your question:
YouTube Android Player API
YouTube Data API Client Library for Java
As the name already suggests, the first library is specifically developed for the Android platform. Its focus is on enabling you to incorporate video playback functionality into an app by providing a player framework. If your goal is to enable users to simply play YouTube videos, then is probably easiest to implement. Do note that this library requires the official YouTube app to be installed on the device.
The second library is more generic (although there are separate instructions for using it on Android) and provides a wrapper around YouTube's Data API to make interfacing with it a little easier. Hence, it allows you to do basically everything you can also do with the web API. As such, it solves a different problem than the Android Player API and is more likely the way to go if you want full control over how you display video data in your own UI.
Your third option would be to do exactly what you did for your web-based solution: make the API call yourself, parse the response and bind up the relevant data to your UI components. Various networking libraries (i.e. Retrofit) can greatly simplify this process.
Refer my post here. I just tried this method for my project and it works very nicely. You don't need the above code or any google api jar imports. Just replace the HTTP request with your HTTP request.
Output is returned in JSON, for which you can use a JSON parser jar to retrieve the title,thumbnails and other details you may require, as I have described in my answer there.
Try this:
protected void requestYoutubeVideos(String text) {
try {
youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("My app name").build();
// Define the API request for retrieving search results.
YouTube.Search.List query = youtube.search().list("id");
// Set your developer key from the Google Cloud Console for
// non-authenticated requests. See:
// https://cloud.google.com/console
query.setKey(YOUTUBE_API_KEY);
query.setQ(text);
query.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
// To increase efficiency, only retrieve the fields that the
// application uses.
query.setFields("items(id)");
query.setOrder("viewCount");
// Restrict the search results to only include videos. See:
// https://developers.google.com/youtube/v3/docs/search/list#type
query.setType("video");
SearchListResponse searchResponse = query.execute();
List<SearchResult> list = searchResponse.getItems();
Log.e("Youtube search", "list ===> " + list);
//Get Info for each video id
for (SearchResult video: list) {
youtubeList.add(video);
YouTube.Videos.List query2 = youtube.videos().list("id,contentDetails,snippet,statistics").setId(video.getId().getVideoId());
query2.setKey(YOUTUBE_API_KEY);
query2.setMaxResults((long) 1);
query2.setFields("items(id,contentDetails,snippet,statistics)");
VideoListResponse searchResponse2 = query2.execute();
List<Video> listEachVideo = searchResponse2.getItems();
Video eachVideo = listEachVideo.get(0);
}
} catch (GoogleJsonResponseException e) {
Log.e("Youtube search", "There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (IOException e) {
Log.e("Youtube search", "There was an IO error: " + e.getCause() + " : " + e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
}
and do not forget to call it from another thread:
new Thread(new Runnable() {
#Override
public void run() {
try {
requestYoutubeVideos("Harry el Sucio Potter");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();

android-json-rpc, receiving invalid response

I am trying to get responses from a JSON-RPC Service on Android, I'm currently developing on 3.0 Honeycomb.
This is the library I am using:
http://code.google.com/p/android-json-rpc/
and I am using this JSON-RPC service page for testing:
http://www.raboof.com/projects/jayrock/demo.ashx
The connection seems to work, but I keep getting this Exception
org.alexd.jsonrpc.JSONRPCException: Invalid JSON response
I've tried different methods and survey pages, but I always get the same Exception. Where am I going wrong?
The relevant code is below. AsyncTask is used because since 3.0 Android doesn't allow network connections in the main stream. Thanks in advance.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
JSONHandler task = new JSONHandler();
task.execute(new String[] {"http://www.raboof.com/projects/jayrock/demo.ashx"});
}
private class JSONHandler extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
for (String url : urls) {
JSONRPCClient client = JSONRPCClient.create(url);
client.setConnectionTimeout(2000);
client.setSoTimeout(2000);
try {
client.call("counter");
} catch (JSONRPCException e) {
e.printStackTrace(); //Invalid JSON Response caught here
}
}
return null;
}
}
I have tested your system using the last version of the library. It work great. You need to us callInt("counter") and it will be ok.
There is the code I used:
public JSONRPCClient client = JSONRPCClient.create("http://www.raboof.com/projects/jayrock/demo.ashx", JSONRPCClient.Versions.VERSION_2);
try{
int resInt = client.callInt("counter");
} catch (JSONException e) {
Log.i("JSON-RPC Client", e.toString());
}
I hope this can help.
PS: with this new version, you use parameters send as an array, or using a JSONObject to send named parameters. This is only possible if using the version 2.0 of the JSON-RPC protocol.
This is the only JSON-RPC client I've been able to get to work with Zend_Json_Server on Android (and I've tried a few).
Make sure to set the version to 2.0 also, as this client doesn't work unless your server is explicitly using the 2.0 spec:
$server = new Zend_Json_Server();
$server->setClass('My_Class');
$server->getRequest()->setVersion("2.0");
if ('GET' == $_SERVER['REQUEST_METHOD']) {
// Indicate the URL endpoint, and the JSON-RPC version used:
$server->setTarget('/ajax.php')
->setEnvelope(Zend_Json_Server_Smd::ENV_JSONRPC_2);
// Grab the SMD
$smd = $server->getServiceMap();
// Return the SMD to the client
header('Content-Type: application/json');
echo $smd;
return;
}
$server->handle();

Categories

Resources