HttpURLConnectionクラスを使用して、サーバーに画像をアップロードします。
String urlStr= "url link";
String response;
boolean isGetMethod = false;
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
DataOutputStream dataOutputStream;
String lineEnd = "\r\n", twoHyphens = "--", boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
File file;
int maxBufferSize = 1024 * 1024;
FileInputStream fileInputStream;
try {
URL url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
if (!isGetMethod) {
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
file = new File("image file path");
fileInputStream = new FileInputStream(file);
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\"" + lineEnd);
dataOutputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
dataOutputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dataOutputStream.flush();
dataOutputStream.close();
}
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuilder builder = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null) {
builder.append(inputLine);
}
response = builder.toString();
bufferedReader.close();
} else
return response;
} catch (Exception e) {
e.printStackTrace();
}
httpURLConnection.disconnect();
return response;
}
@Override
protected void onPostExecute(String response) {
}
}