upload image to php server in android - android

i'm not able to post the image to php server.
i have the code that i found while searching but my question is that how to pass username, password,module and function name in in the current request.
this is the code that i found on most of the sites.
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = "/data/file_to_send.mp3";
String urlServer = "http://192.168.1.1/handle_upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
try
{
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
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(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
//Exception handling
}
i'm getting stuck here..any help is appreciated
Thanks

public static String UplaodData(byte[] data , String text, String id, boolean personalCheck, boolean privateCheck, String ImageName, boolean isClaimNote, String url, String percentage, boolean showProgress)
{
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
//String claimId = ClaimList.claimId;
String noteType = null;
String isImageFile = null;
String Responce = "";
String urlServer = url;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
System.out.println("Value of note type----------------------- "+noteType);
try
{
URL url1 = new URL(urlServer);
connection = (HttpURLConnection) url1.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
if (data != null)
{
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; Content-type: image/png; name=\"attachment\"; filename=\""+ImageName+"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.write(data, 0, data.length);
outputStream.writeBytes(lineEnd);
}
if(isClaimNote){
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"claimId\"" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(id);
outputStream.writeBytes(lineEnd);
}else{
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"activityId\"" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(id);
outputStream.writeBytes(lineEnd);
if(showProgress){
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"activityResolution\"" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(percentage);
outputStream.writeBytes(lineEnd);
}
}
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"noteType\"" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(noteType);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"noteText\"" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(text);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"isImageFile\"" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(isImageFile);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
inputStream = new DataInputStream( connection.getInputStream());
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = "";
while ((serverResponseMessage = inputStream.readLine()) != null)
{
Responce = Responce + serverResponseMessage;
}
outputStream.flush();
outputStream.close();
return Responce;
}
catch (Exception ex)
{
Responce = ex.toString();
return Responce;
}
}
Above is working code to upload multiparty data, customize this as per you parameter list

Related

how to add token in httpurlconnection class

i am using this code for API access.But i have no idea how to add token as header in httpurlconnection class.my tag for token is "token".I want to add "token" tag with token value in header field but i have no idea.i have googled but i am confused
public JSONObject makeHttpRequest(String murl, Utils.method m, Map<String, String> parmas, String Token, String filepath, String filefield, String filemimetype){
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
String urlTo = SERVER_PATH + murl;
String result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
URL url = new URL(urlTo);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
// connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
if (Token != null){
connection.setRequestProperty("token", "Basic " + new String(Base64.encode(Token.getBytes(), 0)));
}
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
if (filepath != null) {
String[] q = filepath.split("/");
int idx = q.length - 1;
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + filemimetype + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
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(lineEnd);
}
// outputStream.writeBytes(getQuery(parmas));
Iterator<String> keys = parmas.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = parmas.get(key);
System.out.println("Key :"+key+" and Value :"+value);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(value);
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
System.out.println("Response Code :"+connection.getResponseCode());
if (200 != connection.getResponseCode()) {
}
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
jobj = new JSONObject(result);
inputStream.close();
outputStream.flush();
outputStream.close();
connection.disconnect();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return jobj;
}

Upload file using HttpURLConnection

I've copied the following code from here, the one thing that I have replaced is using Map instead of the split as shown in commented lines below, my code start right after it.
This code works perfectly all the time except with one device where it fails sometimes, the code seems to be stuck inside this block, I didn't get any exception btw, it just stuck there.
while (iter.hasNext()) {
....
}
Update
I don't have physical access to the phone so I printed a log for each line, even the exception, and I see that the code is stuck in the loop mentioned above, and also note that the http parameters are fixed to 4.
I put a Log inside it and I see that it reached that block and finished all the params and then didn't get out of it, what am I doing here?
public ResponseObject multipartRequest(String urlTo, String post, Map httpPara, String filepath, String filefield) throws ParseException, IOException {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
int ResponseCode;
String twoHyphens = "--";
String boundary = "*****"+Long.toString(System.currentTimeMillis())+"*****";
String lineEnd = "\r\n";
String result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String[] q = filepath.split("/");
int idx = q.length - 1;
try {
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlTo);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
Log.i(Commons.TAG, "filepath " + getMimeType(filepath) );
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] +"\"" + lineEnd);
// outputStream.writeBytes("Content-Type: video/mp4" + lineEnd);
outputStream.writeBytes("Content-Type: " + getMimeType(filepath) + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
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(lineEnd);
// Upload POST Data
// String[] posts = post.split("&");
// int max = posts.length;
// for(int i=0; i<max;i++) {
// outputStream.writeBytes(twoHyphens + boundary + lineEnd);
// String[] kv = posts[i].split("=");
// outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd);
// outputStream.writeBytes("Content-Type: text/plain"+lineEnd);
// outputStream.writeBytes(lineEnd);
// outputStream.writeBytes(kv[1]);
// outputStream.writeBytes(lineEnd);
// }
//
Iterator iter = httpPara.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry para = (Map.Entry) iter.next();
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + para.getKey().toString() + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain"+lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(para.getValue().toString());
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
outputStream.flush();
outputStream.close();
ResponseCode = connection.getResponseCode();
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
fileInputStream.close();
inputStream.close();
return new ResponseObject(ResponseCode, result);
} catch(Exception e) {
Log.e("MultipartRequest","Multipart Form Upload Error");
e.printStackTrace();
return null;
}
}

Upload chunks of file Android

I've copied the following code from here, I'm trying to upload chunks of the file to monitor the progress, is it correct to flush the stream as shown in the code below and use it as a progress? the code i'm asking about is surrounded by stars
public String multipartRequest(String urlTo, Map httpPara, String filepath, String filefield) throws ParseException, IOException {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****"+Long.toString(System.currentTimeMillis())+"*****";
String lineEnd = "\r\n";
String result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String[] q = filepath.split("/");
int idx = q.length - 1;
try {
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlTo);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] +"\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + getMimeType(filepath) + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
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.flush(); *********
///////////***********************/////////////
}
outputStream.writeBytes(lineEnd);
Iterator iter = httpPara.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry para = (Map.Entry) iter.next();
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + para.getKey().toString() + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain"+lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(para.getValue().toString());
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
return result;
} catch(Exception e) {
Log.e("MultipartRequest","Multipart Form Upload Error");
e.printStackTrace();
return null;
}
}
you can call flush() on DataOutputStream any time, there is no restrictions. It will automatically call flush on underlying connection, so your server should receive that chuck of data immediately, which you can use as progress update.
See here for additional reference
The flush method of DataOutputStream calls the flush method of its underlying output stream.

How to Upload large files using ChunkedStreaming in android?

I need to post some large files to server. I am able to upload the files which are < 3 MB , but while i am uploading a file which is > 3 MB, it shows me the Internal server exception and server response code "500". Initially, I thought it is a server side issue but I can post the large file through iOS app(By using the same url), same way I need to implement it in android.
Here is my code --
public String postMediaDataToServer(String evidenceId, File file) {
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "----WebKitFormBoundarysNDKBMUFqqvzYWGh";
Date date = new Date();
String timestamp = dateFormat.format(date);
String fileName = file.getName();
if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
fileName = "image_" + timestamp + ".jpg";
} else if (fileName.endsWith(".wav")) {
fileName = "audio_" + timestamp + ".wav";
} else if (fileName.endsWith(".mp4")) {
fileName = "video_" + timestamp + ".mp4";
} else if (fileName.endsWith(".3gp")) {
fileName = "video_" + timestamp + ".3gp";
}
String response = "error";
Log.e("Image filename", fileName);
Log.e("url", ApplicationData.getBaseUrl()
+ "Media");
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
// DataInputStream inputStream = null;
String pathToOurFile = fileName;
String urlServer = ApplicationData.getBaseUrl()
+ "Media";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(1000*1024);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("X-Ecordia-Software", "ecordiApp");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="
+ boundary);
List<Cookie> cookies = ApplicationData.getCookieStore()
.getCookies();
if (cookies.size() > 0)
connection.setRequestProperty("Cookie", cookies.get(0).getName() + "="
+ cookies.get(0).getValue());
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"EvidenceIdentifier\""
+ lineEnd + lineEnd);
outputStream.writeBytes(evidenceId + lineEnd);
outputStream.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
outputStream.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd + lineEnd);
} else if (fileName.endsWith(".mp4")) {
outputStream.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: video/mp4" + lineEnd + lineEnd);
} else if (fileName.endsWith(".wav")) {
outputStream.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: audio/wav" + lineEnd + lineEnd);
}
outputStream.writeBytes(lineEnd + twoHyphens + boundary + twoHyphens
+ lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.e("Image length", bytesAvailable + "");
try {
while (bytesRead > 0) {
try {
outputStream.write(buffer, 0, bufferSize);
} catch (OutOfMemoryError e) {
e.printStackTrace();
response = "outofmemoryerror";
return response;
}
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
} catch (Exception e) {
e.printStackTrace();
response = "error";
return response;
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("Server Response Code ", "" + serverResponseCode);
Log.i("Server Response Message", serverResponseMessage);
if (serverResponseCode == 200) {
response = "true";
}
fileInputStream.close();
outputStream.flush();
outputStream.close();
outputStream = null;
} catch (Exception ex) {
// Exception handling
response = "error";
Log.e("Send file Exception", ex.getMessage() + "");
ex.printStackTrace();
}
return response;
How to solve this issue?

upload file to server(IIS) by android phone

i googled about my problem but didn't find any thing.
I create a server in win 7 to uploading file from android phone to it.but I can't upload file.
I don't know Is server setting/config is true?![server1][1]
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = "/sdcard/test.txt"; //complete path of file from your android device
String urlServer = "http://www.rar.com/";// complete path of server
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
Log.i("*******urlServer**1**", "urlServer ");
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
Log.i("*******fileInputStream******", "sent: ");
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
Log.i("*******HttpURLConnection**1**", "v ");
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
Log.i("*******setRequestProperty**1**", "v ");
outputStream = new DataOutputStream(connection.getOutputStream());
Log.i("*******DataOutputStream******", "DataOutputStream: ");
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
Log.i("*******lineEnd******", "writeBytes: ");
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.i("*******befwhile******", "byteread ");
Log.i("*******byteread******", String.valueOf(bytesRead));
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
Log.i("*******befwhile******", "end while ");
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
Log.i("*******befwhile******", "twoHyphens ");
// Responses from the server (code and message)
int serverResponseCode = 0;
String serverResponseMessage = "";
serverResponseCode = connection.getResponseCode();
Log.i("*******befwhile******", "getResponseCode1 ");
serverResponseMessage = connection.getResponseMessage();
Log.i("*******befwhile******", "getResponseMessage2 ");
fileInputStream.close();
outputStream.flush();
outputStream.close();
Log.i("*******Sending******", "sent: Final***");
}
catch (Exception ex) {
Log.i("*******exception&&" + ex.toString(), ex.getMessage());
//Exception handling
}
also I don't meaning of outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile + "\"" + lineEnd);
when I runned above code ,it run til
Log.i("**befwhile*", "twoHyphens ");
please help me!
From the documentation url.openConnection() return URLConnection not HttpURLConnection so the method getResponseCode() not exist. Your downcast to HttpURLConnection will not work. Also all data will be send after flush method.

Categories

Resources