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.
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/
I'm using OkHttp in Android Studio.
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.
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.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);
}
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);
}
}
}
}
}
The story of using OkHttp for the first time https://qiita.com/LyricalMaestro0/items/698c77f5a964b5658bbb
Recommended Posts