Android: What is the best HTTP library for files? - android

Hy guys!
I am working on an android project(java) with another guy working on the server-side(php). In my application I need to call POST and GET methods in order to upload files to server, download files, send Strings, byte[] array etc.
My question is: What is the best library to use in my case?(I think my files will not exceed 3mb)
I am new in android so I tried so far:
1.Android Asynchronous Http Client(com.loopj.android:android-async-http:x.x.x)
-we gave up to this because it is not from a "trusted" source
2.AsyncTask+HttpClient+HttpPost
-we gave up to this too
3.Volley library
-best so far(for strings, image request), but it needs additional libraries to send images to server(org.apache.httpcomponents:httpmime:4.5)
-I followed so examples from here but I got exceptions, error, libraries error(duplicates) and never managed to solve one without other showing up.
-so I gave up on this too
My question posted for volley library here
4. Now I am thinking about using Retrofit, but dont know it fits my needs:
-send strings and all types of primitive data
-send image/images to server(together with an Api key)
-download image/images from server
Tell me if I am wrong somewhere or if I missed something working with the libraries specified above. I managed to send simple data with all of these, but I didnt managed to send Files(excepting loopj library).
Do you think should I go back to Volley, or starting reading about Retrofit? Volley seems to be the most flexible one, but not for uploading files.
Any reference or advice is welcome! Thanks in advance!
Update:
I found a possible solution for my problem:
-I convert my file/image to a byte array and encode it to a base64 string
-I send the string to server as basic StringRequest with HashMap<String,String>(Using Volley library from Google developers)
-The server decode the string a save the file

I think a very good fit for you would be AndroidAsync.
You can find more about it on their GitHub repository here: https://github.com/koush/AndroidAsync
As an example for you on how to upload files to server:
AsyncHttpPost post = new AsyncHttpPost("http://myservercom/postform.html");
MultipartFormDataBody body = new MultipartFormDataBody();
body.addFilePart("my-file", new File("/path/to/file.txt");
body.addStringPart("foo", "bar");
post.setBody(body);
AsyncHttpClient.getDefaultInstance().execute(post, new StringCallback() {
#Override
public void onCompleted(Exception e, AsyncHttpResponse source, String result) {
if (e != null) {
ex.printStackTrace();
return;
}
System.out.println("Server says: " + result);
}
});
There is also NanoHTTPD which you can find here: https://github.com/NanoHttpd/nanohttpd
I hope this will help you.

You should try HttpURLConnection its really easy to send data to a server.
https://developer.android.com/training/basics/network-ops/connecting.html

Related

Android WebRTC Receiving a JSON from a javascript PeerJS browser

my app is using WebRTC to communicate with a browser using Chrome (PeerJS), actually multiple browsers. So, whenever I create a block within the browser, the peers are supposed to pass to each other the info of that browser, as far as I know it should be a JSON. The thing is, I cannot get to format it the right way, there are always messed up characters in the message I receive, even if the information like previous block are correct. I just feel like this shouldn't be happening.
I'm trying to figure out what is going on, I feel like PeerJS is doing something more other than sending just a pure JSON. When my app communicate through WebSockets for Offer/Answer/Candidate, all their JSON comes in a normal formating.
My code for onMessage for my RTC Datachannel is:
#Override
public void onMessage(DataChannel.Buffer buffer) {
Charset utf8 = Charset.forName("UTF-8");
ByteBuffer byteBuffer = buffer.data;
CharBuffer charBuffer = utf8.decode(byteBuffer);
Log.d(TAG, "onMessage: " + byteBuffer.toString());
Log.d(TAG, "onMessage: " + charBuffer.toString());
}
The messages I get from the browsers:
��typem�data��type�block��header��index�timestamp�����d�o���previousHash���#0ff530e5a7f0f7d88189e1a87c380cbe0a1a5de9a904278c4831592b0bfd7017�hash���#0d15980b550ce37fe347d08d27e7806980aa8fb65663e667c9c6630de7d69e8e�data��type�ART�timestamp�����d�o���contexthash���#a46887f22840ca5e7ac2368e1c090b3feab8f238788be71864831b48cac45a8f���requestingAcessPKey���VbBtHUR-LkiTMYpxrcF9MofNFa_fgHWLTQkpfSEvo1nksRmsUBiiG7k9eNbOjZ4IDPp61IO4BnA7hz4JiahslxM�signedMsg����0645fc574d2a2ea04018baf91f3b030dea3a4b66a862ae7ad5d6bd8c9d35ddbd18f49b853d75fd7578361046e28104bc6565c2aeb7df7aa7ea120851ea4b6fbf
Also, the message is in a binary format.
Answering my own question. The problem was that PeerJS uses a JS-binary serialization library, in order to deserialize it I needed to write that lib into Java code.
There was no way with raw Android/Java to do it.
The JS library is called binarypackJS.
(Also worth mentioning, that you can actually use JSON to communicate with peerJS, all you need to do is to enable msg type as 'json' and not 'binary'.

Swift Library for Access API

I'm new in iOS development. I have a little experience in Android development and wanna to learn iOS development. In Android i use Retrofit library to access API.
And now i want to know kind of library for access API. I want to discuss about API library that have good performance, easy to use, and easy to understand. yeah of course i already try to find it and i get it :
https://medium.com/ios-os-x-development/restkit-tutorial-how-to-fetch-data-from-an-api-into-core-data-9326af750e10
But i need more idea about library for access API, can anyone help me?
Thank you.
you can Alamofire in ios.
Alamofire.request("https://httpbin.org/get").responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
Even though Alamofire might seem like a good choice for networking, the native URLSession along with the Codable protocol provide the same functionality without adding any dependencies to your project.
let task = URLSession.shared.dataTask(with: url) { data, response, error in
// Handle data, response, and error
}
task.resume()
In iOS, the only library that's ruling on networking is Aalmofire. It simplifies all your networking calls struggles. It provides simple methods to access data from the server. Alamofire is in swift. If you want to create a project in objective C, the same library available in Objective C as AFNetworking.
Below is the example of writing api calls:
let url = ""
let headers = [ "Content-Type" : "application/json"]
let para : Parameters = [ "data" : JSONObject]
Alamofire.request(url, method: .post, parameters: para, encoding: JSONEncoding.default, headers : headers)
.responseJSON { response in
print(response)
print(response.result)
}
Note: As you are a beginner I didn't tell about URLSessions(provided by Apple) which is the perfect way of writing API calls. But it's a very good choice in future.
URLSession built-in possibility
AFNetworking is an Objective-C networking library
Alamofire uses AFNetworking inside but it is written in Swift
SDWebImage image downloader with cache support

Send an image to a server using HttpURLConnection

I have to send an image to a server (I think the best option is using HttpURLConnection) and recieve from it a String answer. In the different docuemnts and web sites that I have read, I have investigated that the best way to do this is using MultipartEntity.
1_ Is it the best solution to do it?
2_ I had an error which says that Android Studio cannot resolve the symbol 'MultipartEntity'. I read that to solve it I have to download external libraries. Which are them and how can I download them?
3_ For this I want to run this process in backGround, but I have a mistake writing the AsyncTask like AsyncTask<String, Void, String> because I want to recieve the parameters like in the answer from this question (Sending files using POST with HttpURLConnection): String urlString, MultipartEntity reqEntity. How can I do to resolve it?
I think the best option is using HttpURLConnection
Is it the best solution to do it?
Probably not. It's too low-level for multi-part requests.
I had an error which says that Android Studio cannot resolve the symbol 'MultipartEntity'. I read that to solve it I have to download external libraries. Which are them and how can I download them?
Options include, but not limited to
Apache HTTP (which is where MultipartEntity comes from)
OkHttp with a multipart example
VolleyPlus
You can get either using Gradle. For Apache see: Android - MultipartEntity and dependencies, and Okhttp just read their documentation where it says "Gradle"
For this I want to run this process in Background
Can't remember about Apache, but OkHttp already can handle that without an AsyncTask.

Right approach for simple Android app [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I've been studying a lot about Android development recently and to really get the feeling of it, I want to start building a simple application that would get me going. Unfortunately, I think the more I read, the more confused I get.
I want to build an app that scans and reads a bar code, queries a RESTful web service with the EAN read from the bar code and outputs the name of the product.
Now, the scanning part was easy, as I used the zxing library as an intent service. Then, I played a lot with a framework called Volley which is supposed to handle the network communication with the web service and parsing the JSON result. Unfortunately, I wasn't able to integrate Volley with my app, but maybe this handy tool is more than I actually need.
What would be the right approach to achieve the above goal? Do I need a content provider? Do I need a service? How would these relate to each other?
I haven't worked with Volley myself, so I can't give you an answer if it's too advanced for what you want to achieve. In general when it comes to HTTP communication with a server I prefer to use AndroidAsyncHttpClient:
"An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. All requests are made outside of your app’s main UI thread, but any callback logic will be executed on the same thread as the callback was created using Android’s Handler message passing."
Example relevant to what you want to do:
public class YourActivity extends Activity {
private void handleScannedBardcode(String barcode) {
// you need to make the request match the REST API you are using
RequestParams params = new RequestParams();
params.put("A_KEY_TO_IDENTIFY_THE_PARAMETER", barcode);
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://www.yourserver.com", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
// you need to add parsing of JSON data to match the response
JSONObject jo = new JSONObject(response);
String productName = jo.getString("productname");
updateProductView(productName);
}
});
}
private void updateProductView(String productName) {
// you need to use a view id that corresponds to a textview in your layout xml
TextView tv = (TextView)findViewById(R.id.productName);
tv.setText(productName);
}
}
Depending on how complex the JSON response is you can either opt for GSON or Jackson for parsing of large amounts of JSON or plain JSONObject
I use this library to handle the communication with my API: https://github.com/koush/ion
It's easy to use, has samples and code examples.
Go with simple solution first:
use HttpURLConnection to connect with web service,
then use either InputStreamReader or BufferedInputStream to read the input stream from the connection.
Create a JSON model class similar to the one you get from your web service.
Use Google GSON library to parse the response into a JSONResponse and then use the data.
I'm sure you'll be able to find enough help on SO regarding these individual points to get you started.

Send and retrieve Ruby on Rails query?

I don't know anything about Ruby, but I think what I'm trying to do is pretty simple. I have an app that needs to send a url query like this to a heroku database: http://dartmouth.heroku.com/dnd/search.json?query=sebastian, then receive the data that comes back and organize it for the user. How do I send and recieve a query like this?
EDIT: I downloaded Spring and added the rest template jar to my projects build path. I tried using this code:
String url = "http://dartmouth.heroku.com/dnd/" + dataBase + "json?query=" + searchContent;
RestTemplate rstTemplate = new RestTemplate();
PersonList pList = rstTemplate.getForObject(url, PersonList.class);
but "RestTemplate" is not recognized. Did I miss an installation step?
You need to start by making an HTTP request for the data and then parsing the results. I would suggest trying out the Spring Android library to accomplish this: http://www.springsource.org/spring-android
Check out the explanation here: http://mike.bailey.net.au/2011/02/json-with-ruby-and-rails/
You can use a plugin called HttpParty for sending the request. Ruby on rails will interpret the json response by using the json library. The example on the above mentioned page might make things clearer.

Categories

Resources