0

Android now recommends using HttpUrlConnection for http requests.

However, there does not seem to be a nice way to post files. With the old HttpClient library, it was pretty straightforward (How do I send a file in Android from a mobile device to server using http?)

But, this seems to be the best solution I can find for HttpUrlConnection Sending files using POST with HttpURLConnection

While that solution works, it is a lot of wheel-reinventing to solve a really common problem. I feel like there must be a better way. I just can't seem to find it.

Community
  • 1
  • 1
fullmeriffic
  • 236
  • 2
  • 14

1 Answers1

1

This may be a little too different than what you were looking for (as it doesn't directly use httpurlconnection), but if you're up for a bit of a change, or if it's still early in your development process (or maybe even if you're not), I'd recommend looking into something like Retrofit to handle all of your networking stuff: http://square.github.io/retrofit/

If you wanted to go that way, you could do something like this: https://futurestud.io/blog/retrofit-how-to-upload-files/

I've done similar things in my own work, but can't really share it, so I'll copy selected parts of the code from that article. As you can see, it's pretty simple.

Service:

@Multipart
@POST("/upload")
void upload(@Part("myfile") TypedFile file,
            @Part("description") String description,
            Callback<String> cb);

Making a request:

FileUpload Service service = ServiceGenerator.createService(FileUpload.class, FileUpload.BASE_URL);
TypedFile typedFile = new TypedFile("multipart/form-data", new File("path/to/your/file"));
String description = "hello, this is description speaking";
service.upload(typedFile, description, new Callback<String>() {
    @Override
    public void success(String s, Response response) {
        Log.e("Upload", "success");
    }

    @Override
    public void failure(RetrofitError error) {
        Log.e("Upload", "error");
    }
});

Again, sorry if this doesn't solve your specific problem, but I think it does solve your "wheel-reinventing to solve a really common problem" part, anyway.

ajpolt
  • 1,002
  • 6
  • 10