I have tried relentlessly to create a succesfull file upload from my JAVA/Android project to Django/Python backend.
The file I am trying to upload is a wav audio file which is stored on the phone.
I am trying to mix two sets of code.
The Android code I am using is the one taken from: How to upload a WAV file using URLConnection.
public class curlAudioToWatson extends AsyncTask<String, Void, String> {
String asrJsonString="";
#Override
protected String doInBackground(String... params) {
String result = "";
try {
Log.d("Msg","**** UPLOADING .WAV to ASR...");
URL obj = new URL(ASR_URL);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
//conn.setRequestProperty("X-Arg", "AccessKey=3fvfg985-2830-07ce-e998-4e74df");
conn.setRequestProperty("Content-Type", "audio/wav");
conn.setRequestProperty("enctype", "multipart/form-data");
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
String wavpath=mRcordFilePath;
File wavfile = new File(wavpath);
boolean success = true;
if (wavfile.exists()) {
Log.d("Msg","**** audio.wav DETECTED: "+wavfile);
}
else{
Log.d("Msg","**** audio.wav MISSING: " +wavfile);
}
String charset="UTF-8";
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
OutputStream output=null;
PrintWriter writer=null;
try {
output = conn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
byte [] music=new byte[(int) wavfile.length()];//size & length of the file
InputStream is = new FileInputStream (wavfile);
BufferedInputStream bis = new BufferedInputStream (is, 16000);
DataInputStream dis = new DataInputStream (bis); // Create a DataInputStream to read the audio data from the saved file
int i = 0;
copyStream(dis,output);
}
catch(Exception e){
}
conn.connect();
int responseCode = conn.getResponseCode();
Log.d("Msg","POST Response Code : " + responseCode + " , MSG: " + conn.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.d("Msg","***ASR RESULT: " + response.toString());
JSONArray jresponse=new JSONObject(response.toString()).getJSONObject("Recognition").getJSONArray("NBest");
asrJsonString=jresponse.toString();
for(int i = 0 ; i < jresponse.length(); i++){
JSONObject jsoni=jresponse.getJSONObject(i);
if(jsoni.has("ResultText")){
String asrResult=jsoni.getString("ResultText");
//ActionManager.getInstance().addDebugMessage("ASR Result: "+asrResult);
Log.d("Msg","*** Result Text: "+asrResult);
result = asrResult;
}
}
Log.d("Msg","***ASR RESULT: " + jresponse.toString());
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.d("Msg","POST FAILED: " + response.toString());
result = "";
}
} catch (Exception e) {
Log.d("Msg","HTTP Exception: " + e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(String result) {
if(!result.equals("")){
Log.d("Msg","onPostEXECUTE SUCCESS, consuming result");
//sendTextInputFromUser(result);
//ActionManager.getInstance().addDebugMessage("***ASR RESULT: "+asrJsonString);
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}else{
Log.d("Msg","onPostEXECUTE FAILED" );
}
}
}
public void copyStream( InputStream is, OutputStream os) {
final int buffer_size = 4096;
try {
byte[] bytes = new byte[buffer_size];
int k=-1;
double prog=0;
while ((k = is.read(bytes, 0, bytes.length)) > -1) {
if(k != -1) {
os.write(bytes, 0, k);
prog=prog+k;
double progress = ((long) prog)/1000;///size;
Log.d("Msg","UPLOADING: "+progress+" kB");
}
}
os.flush();
is.close();
os.close();
} catch (Exception ex) {
Log.d("Msg","File to Network Stream Copy error "+ex);
}
}
The Django backend code is taken from: https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html and I am using the simple upload:
def simple_upload(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
return render(request, 'core/simple_upload.html', {
'uploaded_file_url': uploaded_file_url
})
return render(request, 'core/simple_upload.html')
I have already disabled the need for CSRF using #csrf_exempt.
I am getting the error "MultiValueDictKeyError" since Java does not post the file with the name 'myfile' for request.FILES['myfile'] to catch. Is have tried removing the ['myfile'] and just use request.FILES but then I get an error on
filename = fs.save(myfile.name, myfile)
saying there is no name to fetch.
Can I post the file so that it it catched by
request.FILES['myfile']
or is there better/simpler Django backend-code to use for communication with Android/IOS.
Thanks in advance and I apologize if this is a stupid question but I am dead stuck.
Here I go again answering my own question.
I found the following code from Android:How to upload .mp3 file to http server?
Using that instead of How to upload a WAV file using URLConnection and changing the line: dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
To dos.writeBytes("Content-Disposition: form-data; name=\"myfile\";filename=\"" + existingFileName + "\"" + lineEnd);
fixed my problem.
Related
I want to upload Image to Perticular Url(www.myUrl.com/myFolderName/) through android and retrieve the address of that url.
Here is my code
class SaveFile extends AsyncTask<String,String,String>
{
FileInputStream fileInputStream;
HttpURLConnection connection;
URL url;
DataOutputStream outputStream;
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedImagePath);
//selectedImagePath = path of Image in phonememory
#Override
protected String doInBackground(String... params)
{
Log.v(TAG,"Image path is " + selectedImagePath);
try
{
fileInputStream = new FileInputStream(selectedFile);
url = new URL(SEND_IMAGE);
connection= (HttpURLConnection)url.openConnection();
Log.v(TAG,"connection established");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection","Keep-Alive");
connection.setRequestProperty("ENCTYPE","multipart/form-data");
connection.setRequestProperty("Content-Type","multipart/form-data;boundary=*****");
//connection.setRequestProperty("image1",selectedImagePath);
//connection.setRequestProperty("user_id","1");
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes("--*****\r\n");
outputStream.writeBytes("Content-Disposition:form-data;name=\"uploaded_file\";filename=\""+selectedImagePath+"\""+"\r\n");
outputStream.writeBytes("\r\n");
//outputStream.writeBytes("--*****\r\n");
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer,0,bufferSize);
while (bytesRead>0)
{
outputStream.write(buffer,0,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
}
outputStream.writeBytes("\r\n");
outputStream.writeBytes("--*****--\r\n");
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
if(serverResponseCode == HttpURLConnection.HTTP_OK) {
String line;
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
Log.v(TAG,"Response is " +sb.toString());
}
Log.v("UploadImage", "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception e)
{
Log.v("UploadImage"," " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
but I am getting serverResponse 404
I tried solutions like Uploading Image to Server - Android but not worked.
I searched a lot.but couldnt find solution
Please Help!!
I want to say that this maybe a server error. 404 in most cases is an error that says, "you have used wrong url". Check whether this url is correct.try to upload your data in your browser.
I am wondering here and there from last 2 days. My issue is that I am sending multiple files with some text/plain fields using multipart/form-data.
The issue is that when I am sending data using HTTPCLient its working fine but when I am trying to send data using HTTPURLConnection, server is not receiving anything, below is my MultipartUtility,
public class MultipartUtils extends NetworkUtility
{
private static final String END_REQUEST = "--";
private String mBoundary;
public MultipartUtils()
{
mBoundary = END_REQUEST + "quAxBSd";
}
public HttpURLConnection getUrlConnection(String URL, String httpMethod,
String contenttype, String boundry) throws Exception
{
URL url = new URL(URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (httpMethod.equalsIgnoreCase(HTTP_GET) == false)
urlConnection.setDoInput(true);
else
urlConnection.setDoInput(false);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestMethod(httpMethod);
if (contenttype.equalsIgnoreCase(APPLICATION_MULTIPART))
{
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundry);
urlConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
}
else
{
urlConnection.setRequestProperty("Content-Type", contenttype);
}
return urlConnection;
}
public String uploadImagesAddPost(Activity mContext, String URL, String jsonString, ArrayList<ImageListBean> mImageBeanList) throws Exception
{
HttpURLConnection httpURLConnection = getUrlConnection(URL, HTTP_POST, APPLICATION_MULTIPART, mBoundary);
httpURLConnection.connect();
DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
PrintWriter writer = new PrintWriter(new OutputStreamWriter(dataOutputStream, UTF8),
true);
addJsonToPart(writer, jsonString);
for (int i = 0; i < mImageBeanList.size(); i++)
{
try
{
byte[] imageByteArray = {};
Uri imageUri = mImageBeanList.get(i).getmUri();
String imagePath = ImageCaputureUtility.getPath(imageUri, mContext);
if (!imagePath.equals(""))
{
if (mImageBeanList.get(i).getmType().equalsIgnoreCase(MellTooConstants.IMG))
{
//For img
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, outputStream);
imageByteArray = outputStream.toByteArray();
addFileAsByte(dataOutputStream, "imageview" + (i + 1), imageByteArray, ("imageview" + (i + 1)) + ".jpeg", IMAGE_JPEG);
}
else
{
//For video
/* Uploading thumb*/
Bitmap bitmap = UtilsMellToo.createThumb(imageUri, mContext);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, outputStream);
imageByteArray = outputStream.toByteArray();
addFileAsByte(dataOutputStream, "imageview4", imageByteArray, "imageview4" + ".jpeg", IMAGE_JPEG);
/* Uploading video*/
imageByteArray = MellTooUtil.readFileToByteArray(new File(imagePath));
addFileAsByte(dataOutputStream, "video", imageByteArray, "video" + (i + 1) + ".mp4", VIDEO_MP4);
}
}
else
{
//No need to upload data
}
}
catch (Exception e)
{
e.printStackTrace();
}
if (i + 1 != mImageBeanList.size())
writer.append(mBoundary).append(CHANGE_LINE);
}
writer.append(mBoundary + END_REQUEST);
writer.flush();
return getResponse(httpURLConnection);
}
private void addJsonToPart(PrintWriter writer, String text)
{
writer.append(mBoundary).append(CHANGE_LINE);
writer.append(CONTENT_DISPOSITION + FORM_DATA + NAME + "\"formstring\"").append(CHANGE_LINE);
writer.append(CONTENT_TYPE + PLAIN_TEXT + CHARSET + UTF8).append(CHANGE_LINE);
writer.append(CONTENT_TRANSFER_ENCODING + "8bit").append(CHANGE_LINE);
writer.append(text).append(CHANGE_LINE);
writer.flush();
}
public void addFileAsByte(DataOutputStream outputStream, String fieldName, byte[] imageByteArray, String fileName, String contentType) throws IOException
{
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, UTF8),
true);
writer.append(mBoundary).append(CHANGE_LINE);
writer.append(CONTENT_DISPOSITION + FORM_DATA + NAME + "\"" + fieldName + "\";" + FILE_NAME + "\"" + fileName + "\"").append(CHANGE_LINE);
writer.append(CONTENT_TYPE + contentType).append(CHANGE_LINE);
writer.append(CONTENT_TRANSFER_ENCODING + BINARY).append(CHANGE_LINE);
writer.flush();
InputStream inputStream = new ByteArrayInputStream(imageByteArray);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.writeBytes(CHANGE_LINE);
outputStream.flush();
inputStream.close();
}
}
Below is the method, how I am using this class,
jsonResponseString = new MultipartUtils()
.uploadImagesAddPost(mContext, AppConstants.BASE_URL + AppConstants.SAVE_POST_URL,
mJsonString, mImageList);
Below is my ASP side,
HttpContextWrapper.Request.Form["formstring"]; //This is returning null
Please help me out from this...!!!
Thanks in advance
Below is my request,
After struggling approximately 4 days, I found the issue was in the boundry and the new line in the request....!
There should be a boundary and a blank line between text and image part and I was not using it. The blank line is separating the header from the boday of the each part of a multipart/form-data request...!
I have been hitting my head against a wall on this one.
In my Android App, I select an image. That all seems to be working fine. I then convert it to a byte array and HTTP POST it to a server. The data written to file on the server side does not appear to be what the data started as.
When checking things end-to-end it seems that the file on my device is 1,066,896 bytes. The data on the server is 14,745,600 bytes.
Code from Selecting the Image:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_IMAGE: {
if (resultCode != RESULT_OK)
return;
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
MainActivityFragment fragment = (MainActivityFragment)Fragments.Get("Main");
new SendPic().execute(bitmap);
} catch (IOException exception) {
Log.e(TAG, "Could not load image", exception);
}
break;
}
}
}
If I check bitmap.getByteCount() in the above code, it will report 14,745,600, which makes me relatively confident that the data being sent to the server is good. But I can't figure out while the data read in is 14x larger than what I show on the device. It I take this same bitmap though, and apply it to an ImageView, the image looks just fine.
SendPic is a simple class that extends AsyncTask. No magic there.
public static String SendHttpImage(String path, Bitmap bitmap, String name, String filename) {
String attachmentName = "bitmap";
String attachmentFileName = "bitmap.bmp";
String crlf = "\r\n";
String twoHyphens = "--";
String boundary = "******";
try {
String url = "http://server.com/index.php?" + path;
URL u = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection)u.openConnection();
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Cache-Control", "no-cache");
urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream request = new DataOutputStream(urlConnection.getOutputStream());
request.writeBytes(twoHyphens + boundary + crlf);
request.writeBytes("Content-Disposition: form-data; name=\"" + attachmentName + "\";filename=\"" + attachmentFileName + "\"" + crlf);
request.writeBytes(crlf);
int bytes = bitmap.getByteCount();
ByteBuffer buffer = ByteBuffer.allocate(bytes);
bitmap.copyPixelsToBuffer(buffer);
byte[] pixels = buffer.array();
request.write(pixels);
request.writeBytes(crlf);
request.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
request.flush();
request.close();
InputStream responseStream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();
String response = stringBuilder.toString();
urlConnection.disconnect();
return response;
} catch (IOException exception) {
Log.e (TAG, "HTTP Post failed", exception);
return null;
}
}
Thank you for your help with this!
Many thanks to #Colin Gillespie. I compressed the data to jpeg before sending to the server, and it came out perfect on the other side. I'm still quite confused as to why my browser couldn't display the raw bitmap, but I won't look a gift-horse in the mouth.
i'm trying to send some data to a server. The server is waiting a json and an image. I tried with every example that i found but i couldn't send the data. Actually i'm sending the json params with a PrintWriter object, but it doesn't accept the image. I need to use HttpURLConnection not with the apache library. This is my piece of code working:
HttpURLConnection connection = null;
PrintWriter output = null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
attachImage.compress(Bitmap.CompressFormat.PNG, 40, stream);
byte[] imageData = stream.toByteArray();
String imagebase64 = Base64.encodeToString(imageData, Base64.DEFAULT);
Log.d(tag, "POST to " + url);
try{
URL url = new URL(this.url);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty(HTTP_CONTENT_TYPE, "application/json; charset=utf-8");
connection.setRequestProperty(HTTP_USER_AGENT, mUserAgent);
connection.setRequestProperty(HTTP_HEADER_ACCEPT, "application/json; charset=utf-8");
connection.connect();
output = new PrintWriter(connection.getOutputStream());
JSONObject jsonParam = new JSONObject();
jsonParam.put("oauth_token", params.get("oauth_token"));
jsonParam.put("rating", "1");
jsonParam.put("comments", "ASDASDASDASDASDASDAS");
Log.d(tag, jsonParam.toString());
output.print(jsonParam);
output.flush();
output.close();
Log.d(tag, connection.getResponseCode() + connection.getResponseMessage());
}catch(Exception e ){
}
When I try to send an image in json params, I receive an 500 internal error message.
Thanks!
Okay , as per my suggestion 2 ways to send image to server
use base 64 string
Direct upload to server
1.for base 64 go to below link
Android post Base64 String to PHP
2.for direct upload to server Please check below link
http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/
Happy coding !!
People! After a lot of day, i could upload an image to a server! I was reading this library, which is for a lot of uses. https://source.android.com/reference/com/android/tradefed/util/net/HttpMultipartPost.html
I downloaded the source code, and i took some clases to send an image. I send only bytes, which were encoded from ASCII. Thanks for the help!
Check this below code to send form data and zip file containing images or other any media files.
private class MultipartFormTask extends AsyncTask<String, Void, String> {
String getStringFromInputStream(HttpURLConnection conn) {
String strResponse = "";
try {
DataInputStream inStream = new DataInputStream(
conn.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(
inStream));
String line;
while ((line = br.readLine()) != null) {
strResponse += line;
}
br.close();
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return strResponse;
}
void uploadJSONFeed(HttpURLConnection conn, DataOutputStream dos,
String lineEnd) {
String issue_details_key = "issue_details";
String issue_details_value = "Place your Jsondata HERE";
try {
dos.writeBytes("Content-Disposition: form-data; name=\""
+ issue_details_key + "\"" + lineEnd
+ "Content-Type: application/json" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(issue_details_value);
dos.writeBytes(lineEnd);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
}
void uploadZipFile(HttpURLConnection conn, DataOutputStream dos,
String lineEnd) {
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
InputStream is = null;
try {
is = getAssets().open("Test.zip");
} catch (IOException ioe) {
// TODO Auto-generated catch block
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
String zip_file_name_key = "file_zip";
String upload_file_name = "test.zip";
dos.writeBytes("Content-Disposition: form-data; name=\""
+ zip_file_name_key + "\";filename=\""
+ upload_file_name + "\"" + lineEnd); // uploaded_file_name
// is the Name
// of the File
// to be
// uploaded
dos.writeBytes(lineEnd);
bytesAvailable = is.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = is.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = is.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = is.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
is.close();
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String urlString = "http://www.example.org/api/file.php";
try {
// ------------------ CLIENT REQUEST
// FileInputStream fileInputStream = new FileInputStream(new
// File(existingFileName) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
uploadJSONFeed(conn, dos, lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
uploadZipFile(conn, dos, lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
// ------------------ read the SERVER RESPONSE
String strResponse = getStringFromInputStream(conn);
return strResponse;
}
#Override
protected void onPostExecute(String result) {
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
Log.e("Result:", result);
}
}
you can upload large jsonstring using buffer please use bellow code .
HttpsURLConnection connection = null;
OutputStream os = null;
InputStream is = null;
InputStreamReader isr = null;
try {
connection = (HttpsURLConnection) url.openConnection();
SSLContext contextSSL = SSLContext.getInstance("TLS");
contextSSL.init(null, new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(contextSSL.getSocketFactory());
MySSLFactory(context.getSocketFactory()));
HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(0);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", auth);
connection.setConnectTimeout(timeoutMillis);
OutputStream os ;
if (input != null && !input.isEmpty()) {
os = connection.getOutputStream();
InputStream stream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8));
BufferedInputStream bis = new BufferedInputStream(stream, 8 * 1024);
byte[] buffer = new byte[8192];
int availableByte = 0;
while ((availableByte = bis.read(buffer)) != -1) {
os.write(buffer, 0, availableByte);
os.flush();
}
}
int responseCode = connection.getResponseCode();
HTTP 500 error code means a server-side error occured.
This has nothing to do with your code.
The server is having a bug, not your code.
How to send file in POST-query using Apache HTTPComponents?
One possible solution is to generate HTTP headers by yourself, as explained here - http://en.wikipedia.org/wiki/MIME (see "Multipart messages")
I wrote such function. Maybe it is not well-written, but it works great.
private static final String REQUEST_BOUNDARY = "somethingUniqueForYourQuery";
private static String sendRequest(String url, String method, String params, File file, String fileField) {
HttpURLConnection httpConn = null;
StringBuilder httpContent = new StringBuilder();
String lineEnd = "\r\n";
String twoHyphens = "--";
byte[] fileContent = new byte[0];
int fileSize = 0;
// trying to read file
if (file != null) {
try {
FileInputStream fileInputStream = new FileInputStream(file);
httpContent.append(twoHyphens + REQUEST_BOUNDARY + lineEnd);
httpContent.append("Content-Disposition: form-data; name=\"" + fileField + "\"; filename=\"" + file.getName() + "\"" + lineEnd);
httpContent.append(lineEnd);
fileSize = fileInputStream.available();
fileContent = new byte[fileSize];
fileInputStream.read(fileContent, 0, fileSize);
fileInputStream.close();
}
catch (Exception e){
Log.d(DEBUG_TAG, "Exception occured: " + e.toString());
}
}
// trying to perform request
try {
httpConn = (HttpURLConnection) new URL(url).openConnection();
if (httpConn != null) {
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setUseCaches(false);
httpConn.setConnectTimeout(CONNECTION_TIMEOUT_STRING);
httpConn.setRequestMethod(method);
if (file != null && httpContent.length() > 0) {
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + REQUEST_BOUNDARY);
DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
if (params != null) {
dos.writeBytes(params);
}
dos.writeBytes(httpContent.toString());
dos.write(fileContent, 0, fileSize);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + REQUEST_BOUNDARY + twoHyphens + lineEnd);
dos.flush();
dos.close();
}
else if (params != null) {
PrintWriter out = new PrintWriter(httpConn.getOutputStream());
out.print(params);
out.close();
}
httpConn.connect();
int response = httpConn.getResponseCode();
BufferedReader rd;
if (httpConn.getErrorStream() == null) {
rd = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
} else {
rd = new BufferedReader(new InputStreamReader(httpConn.getErrorStream()));
}
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line + "\n");
}
if (rd != null) {
rd.close();
}
return sb.toString();
} else {
Log.d(DEBUG_TAG, "Connection Error");
}
}
catch (Exception e){
Log.d(DEBUG_TAG, "Exception occured: " + e.toString());
}
finally {
if (httpConn != null) {
httpConn.disconnect();
}
}
return null;
}