[Android] Uploading images from your device to the server

Introduction

I had trouble with the function to POST an image on Android and save it on the server, so I write it as my memorandum and output. I haven't worked on the program for half a year, so it may be strange, but please forgive me.

Postscript

I received your point. Thank you!

OkHTTP2 is treated as obsoletes. Make sure to use the latest 4.3.1.

https://square.github.io/okhttp/changelog_3x/#version-300-rc1 https://square.github.io/okhttp/changelog/

environment

I'm using OkHttp in Android Studio.

Introduced OkHttp

implementation 'com.squareup.okhttp:okhttp:2.7.5'

#### **`Added.(2.7.Change 5 depending on the varsion.)~~`**

build.gradle


//~~ Omitted ~~
dependencies{
  //~~ Omitted ~~
  implementation 'com.squareup.okhttp:okhttp:4.3.1'//Postscript
}

Done.

AsyncTask Since it is sent by Http communication, it is done asynchronously.

OkHttpTask.java


import android.os.AsyncTask;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpTask extends AsyncTask<String, Void, String> {

    String responseBody;
    public HttpTask(){}

    @Override
    protected String doInBackground(String... params) {
        String url = "URL to send"; 
        MediaType media = MediaType.parse("multipart/form-data");
        try {
            File file = new File(params[0]);
            String FileName = file.getName();
            String boundary = String.valueOf(System.currentTimeMillis());

            RequestBody requestBody = new MultipartBody.Builder(boundary).setType(MultipartBody.FORM)
                    .addFormDataPart("file", FileName, RequestBody.create(media, file))
                    .build();

            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();

            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            responseBody = response.body().string();

            return responseBody;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseBody;
    }

    @Override
    protected void onPostExecute(String result) {
        Log.d("a",result);
    }
}

I made a lot of changes, so I rewrote it. Also, with the change java.io.IOException: Cleartext HTTP traffic to example.com not permitted You may see an error like this. This is because HTTPS communication is used by default, so it is necessary to write a method to allow HTTP communication. Please see here for details on how to do this.

old code

OkHttpTask_old.java


/**Delete
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
*/
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpTask extends AsyncTask<String, Void, String> {
  public OkHttpTask(){}

    @Override
    protected String doInBackground(String... params) {
        //URL of the post destination
        String url = "http://";
        File file = new File(params[0]);

        /**Delete
        *Set the content to POST here
        RequestBody requestBody = new MultipartBuilder()
                .type(MultipartBuilder.FORM)
                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file))
                .build();
        */

        //Set the content to POST here(Change here)
        RequestBody requestBody = new MultipartBody.Builder()
                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/jpg"), file))
                .build();


        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        String result="";
        try {
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            {
                result = response.body().string();
            }
        } catch (Exception e) {}

        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        Log.d("end:",result);
    }
}
*/
MainActivity

MainActivity.java



public class MainActivity extends AppCompatActivity {
  //URI of the image to send
  private Uri _imageUri;
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Call here
        new OkHttpTask().execute(url);   
}

Recipient

Just save the posted file.

UpLoad.java


@WebServlet("/Upload")
@MultipartConfig(location = "Storage location")
public class upload extends HttpServlet {

	public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException, ServletException {
		String name="no_name";
		//multipart/form-Get all Part elements of this request provided by data
		for (Part part : req.getParts()) {
			//Get name
			for (String cd : part.getHeader("Content-Disposition").split(";")) {
				String str = cd.trim();
				if (str.startsWith("filename")) {
					String str2 = str.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
					File f = new File(str2);
					name = f.getName();
					part.write(name);
				}
			}
		}
	}
}

Reference link

The story of using OkHttp for the first time https://qiita.com/LyricalMaestro0/items/698c77f5a964b5658bbb

Recommended Posts

[Android] Uploading images from your device to the server
POST images from Android to PHP using Retrofit
Vibrate the wristband device with Bluetooth from the Android app
Try switching from the RHEL environment to the Ubuntu environment Server installation
Check communication from Android to node.js server with protocol buffers
Send the accelerometer value from Android to PC via UDP
Stop resending from client to server
[Android, Java] Method to find the elapsed date from two dates
The road from JavaScript to Java
[Android] I want to get the listener from the button in ListView
How to narrow down the image format from the gallery on Android and then select and import multiple images
[Java] How to retrieve the parameters passed from html on the server side
[Android] Check the actual device without moving your hand with automatic scrolling
Investigate the replacement from Docker to Podman.
[Ruby] From the basics to the inject method
Kick ShellScript on the server from Java
* Android * Saving / loading images to external storage
Try using the Emotion API from Android
How to connect to lcalhost from your smartphone and use the app under development
Learn while making a WEB server Introduction to WEB application development from the basics
[Rails] I tried to raise the Rails version from 5.0 to 5.2
Migration from Eclipse to IntelliJ (on the way)
3 ways to import the library in Android Studio
What to do if the server tomcat dies
When the server fails to start in Eclipse
Migrate from Java to Server Side Kotlin + Spring-boot
Ssh login to the app server on heroku
Migrating from Eclipse server function (Tomcat) to Embed Tomcat
Get your version number in the Android app
Minecraft BE server development from PHP to Java
[Android development] Get an image from the server in Java and set it in ImageView! !!