Android httpURLConnection already running - android

I've got an app where in I was calling an httpURLConnection with the requestproperty connection "stay-alive".
Because I didn't call the HttpURLConnection.disconnect() when my app was crashing, he didn't make it to the disconnect call because I didn't put it in the finally method.
Problem
When I rerun my app, I see that my url.openConnection() already see the old HttpUrlConnection and take that back out of the pool. Problem now is that I can't simply kill the already existed connection.
After some research on the web I found an old bug report (https://code.google.com/p/android/issues/detail?id=2939)
I already tried different approaches, but after the url.openConnection() calling httpURLConnection.disconnect() didn't do anthing. Reinstall app, reboot pc and tablet also weren't effective.
Known exceptions
java.lang.IllegalStateException: Already connected
Question
So my question is: How can I kill the existed HttpURLConnection?
Here a brief example of the wrong used code:
try{
File file = new File("resources/test.png");
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlRequest);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//Get Cookie from session
String key = MyHttpClient.sharedInstance().getCookieStore().getCookies().get(0).getName();
String value = MyHttpClient.sharedInstance().getCookieStore().getCookies().get(0).getValue();
//allow inputs & outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
//Enable GET method
connection.setRequestMethod("GET");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("User-Agent", "MyAgent");
connection.setRequestProperty("Cookie", key+"="+value);
//Call with stream fields
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
//Call with stream
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
/*outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""+ Configuration.userTempImage.getPath()+ "\""+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)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
String jsonText = readAll(rd);
fileInputStream.close();
outputStream.flush();
outputStream.close();
System.out.print(serverResponseCode + " - " + serverResponseMessage+" -> ");
} catch (Exception ex){
System.out.print(ex.getMessage());
}
And this is my updated code
private static String getImagePath(String urlRequest){
System.setProperty("http.keepAlive", "false");
// ?
FileOutputStream fos = null;
// The connection to the server
HttpURLConnection connection = null;
// The data steam for sending the file to the server
DataOutputStream outputStream = null;
// A file stream to read the local file.
FileInputStream fileInputStream = null;
// ?
ByteArrayOutputStream stream = null;
// Cropped image file
File croppedImage = null;
try{
try{
stream = new ByteArrayOutputStream();
Configuration.userTempBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
// Close the output-stream
if(stream != null) { stream.close(); }
croppedImage = new File(Environment.getExternalStorageDirectory(), "test.jpg");
if(croppedImage.exists()){
croppedImage.delete();
}
fos = new FileOutputStream(croppedImage);
fos.write(byteArray);
} catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
} finally {
if(fos != null) { fos.close(); }
}
//Get Cookie from session
String key = MyHttpClient.sharedInstance().getCookieStore().getCookies().get(0).getName();
String value = MyHttpClient.sharedInstance().getCookieStore().getCookies().get(0).getValue();
URL url = new URL(urlRequest);
connection = (HttpURLConnection)url.openConnection();
//Allow inputs & outputs
connection.setDoInput(true); // <-- Exception is thrown here
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set connection properties
connection.setRequestProperty("Cookie", key+"="+value);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("User-Agent", "MyAgent");
// Set connection headers
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
//Call with stream fields
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
// Create an input stream to the cropped image file
fileInputStream = new FileInputStream(croppedImage);
// Create an output stream to send the file to the server
outputStream = new DataOutputStream(connection.getOutputStream());
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);
}
// Be sure to send everything
outputStream.flush();
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
String jsonText = RequestHelper.readAll(rd);
return jsonText;
}catch(Exception ex){
ex.printStackTrace();
} finally {
try{
if(fileInputStream != null) { fileInputStream.close(); }
if(outputStream != null) { outputStream.close(); }
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(connection != null) { connection.disconnect(); }
}
}
return null;
}

Related

Httpurlconnection upload file trigger network lost for reset or resume

When I am uploading video to a server (Vimeo) with Android, everything is ok.
But during the upload, if i am loosing the network connection, i can't trigger .write I/O Exception From DataOutputStream.
So my app is freeze.
How can I trigger the exception to resume or reset my upload ?
My try / catch don't trigger the exception…
Here is my code :
private void call_for_ticket(String upload_url, String complet_uri, String videoUri) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(videoUri);
if (sourceFile.isFile())
{
try
{
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upload_url);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("PUT");
conn.setRequestProperty("Authorization",Aurtorizartion);
conn.setRequestProperty("Accept",accept);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "video/mp4");
conn.setChunkedStreamingMode(-1);
try {
dos = new DataOutputStream(conn.getOutputStream());
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
long bytesAvailableReadIncrementation = 0;
long totalFileSize = bytesAvailable;
try{
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math
.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0,
bufferSize);
bytesAvailableReadIncrementation += bytesRead;
publishProgress("" + (long) ((bytesAvailableReadIncrementation * 100) / totalFileSize));
}
} catch (IOException e) {
Log.d("VMA", "lost connection");
e.printStackTrace();
}
// send multipart form data necesssary after file
// data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
int serverResponseCode;
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn
.getResponseMessage();
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
if (serverResponseCode == 200) {
call_complete_uri(complet_uri);
}
}
catch (IOException e)
{
Log.d("VMA", "lost connection");
e.printStackTrace();
}
} catch (IOException e) {
Log.d("VMA", "lost connection");
e.printStackTrace();
}
}
}
Ok So i figure out.
I am testing my code on the simulator.
On a real device, the exception is thrown :).

Out of Memory Issue when encode into base64 video file

I am trying to upload the video file into server with convert into base64. But I am getting out of memory exception even size is 2 mb also. How to resolve this issue. Please help me to over out, much appreciate your help.
Here what I am doing
byte [] ba = convertByteArray(videoUri);
String baseimage=Base64.encodeToString(ba, Base64.NO_WRAP);
public byte[] convertByteArray(Uri videoUri){
InputStream iStream=null;
byte[] inputData=null;
try {
iStream = getContentResolver().openInputStream(videoUri);
inputData = getBytes(iStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return inputData;
}
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
Code :
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://your_website.com/upload_audio_test/upload_audio.php";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
// 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);
dos.writeBytes("Content-Disposition: form-data; name="uploadedfile";filename="" + selectedPath + """ + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.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...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug","File is written");
fileInputStream.close();
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
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("Debug","Server Response "+str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
Go through the following Sample for more reference :
http://coderzheaven.com/2011/08/uploading-audio-video-or-image-files-from-android-to-server/
For uploading video to server see doFileUpload() method from the above url.

android read file and upload

I have a code:
File myFile = new File("/sdcard/Pictures/MyCameraApp/1.jpg");
FileInputStream fin = null;
// create FileInputStream object
try {
fin = new FileInputStream(myFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte fileContent[] = new byte[(int)myFile.length()];
// Reads up to certain bytes of data from this input stream into an array of bytes.
try {
fin.read(fileContent);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//create string from byte array
String s = new String(fileContent);
return new NanoHTTPD.Response(HTTP_OK, "image/jpeg", s);
But when I go with my browser, I see a corrupt JPEG file. what am I doing wrong? I want a user when enters some address to see 1.jpg file
Edit: Changed code to:
File myFile = new File("/sdcard/Pictures/MyCameraApp/1.jpg");
FileInputStream fin = null;
// create FileInputStream object
try {
fin = new FileInputStream(myFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int bytesRead;
try {
while ((bytesRead = fin.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] fileContent = bos.toByteArray();
//create string from byte array
String s = new String(fileContent);
return new NanoHTTPD.Response(HTTP_OK, "image/jpg", s);
Still Doesn't work..... When I enter page, I get corrupt jpg file, (doesn't work either if I write image/jpeg instead image/jpg, or text/html, save the text as jpg file. works perfecly for text :\
How to Read Bytes From a File in Android
The code is only reading the beginning of your file. That is why the bytes that arrive on the server appear as a corrupt image file.
Try these code modifications:
fin = new FileInputStream(myFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((int bytesRead = fin.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] fileContent = bos.toByteArray();
Of course, you'll have to wrap in all of the appropriate Exception handlers.
this solution isn't mine but can be useful, mimics a upload form you can found the source here
class Utils {
public static void upload(String filePath, String urlServer) {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
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
}
}
}
reception code
<?php
$target_path = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>

Opening DataInputStream running very slow

I am uploading a file to a server and depending on the processing on the file I get a different reply from the server. Everything is working, however getting the reply from the server is very slow. I checked in the debugger and the following line of code is taking 6 seconds to run.
inStream = new DataInputStream( connection.getInputStream() );
I have tested the same files and code over a web browser and its perfect, taking about 1 or 2 seconds to display the reply. Here is my full code, I think its ok, but maybe there is something here that is not done properly. Is there a better way of doing this? Or is a new DataInputStream always going to be so slow?
private String loadImageFromNetwork(String myfile) {
HttpURLConnection connection = null;
DataOutputStream outStream = null;
DataInputStream inStream = null;
String make = "";
String model = "";
String disp = "";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String urlString = "http://xxxxxxxxxxxxxx/upload.php";
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + myfile)));
try {
FileInputStream fileInputStream = new FileInputStream(new File(myfile));
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs
connection.setDoInput(true);
// Allow Outputs
connection.setDoOutput(true);
// Don't use a cached copy.
connection.setUseCaches(false);
// Use a post method.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outStream = new DataOutputStream(connection.getOutputStream());
outStream.writeBytes(twoHyphens + boundary + lineEnd);
outStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + myfile +"\"" + lineEnd);
outStream.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outStream.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...
outStream.writeBytes(lineEnd);
outStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
fileInputStream.close();
outStream.flush();
outStream.close();
}
catch (MalformedURLException ex) {
ex.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream( connection.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
disp = disp + str;
}
inStream.close();
}
catch (IOException ioex){
ioex.printStackTrace();
}
return disp;
}
You should move the code to read the response from the server to a new thread. Ex:
private class ReadResponse implements Runnable {
public void run() {
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream( connection.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
disp = disp + str;
}
inStream.close();
}
catch (IOException ioex){
ioex.printStackTrace();
}
//return disp;
//here you need to show your display on UI thread
}
}
}
and start the reading thread before uploading the file.

Uploading MS Word files from Android to .Net WCF?

I have problem in uploading .doc file to .Net WCF from my Android app. I am able to send file but it is not supported on WCF end.
Here is my method for uploading:
protected void checkinmethod(String rid) throws Exception {
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot, rid+".doc");
InputStream in = new FileInputStream(file);
byte[] bytearray=new byte[(int) file.length()];
int ab=0;
do
{
ab=in.read(bytearray, 0, bytearray.length);
} while(ab>0);
InputStream mystream= new ByteArrayInputStream(bytearray);
InputStreamEntity se=new InputStreamEntity(mystream, 10000);
HttpPost request = new HttpPost("http://10.66.52.247/tutorwcf/Service.svc/Service/updateMyDoc1");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/msword");
request.setEntity(se);
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
statuss.setText(new String(buffer));
//
}
catch (Exception e) {
// TODO: handle exception
Log.e("hi", "exception is", e);
statuss.setText("exception");
}
}
here is .net code:
FileStream fileToupload = new FileStream("D:\\myfile.doc", FileMode.Create, FileAccess.Write);
byte[] bytearray = new byte[10000];
int bytesRead, totalBytesRead = 0;
do
{
bytesRead = mystream.Read(bytearray, 0, bytearray.Length);
totalBytesRead += bytesRead;
} while (bytesRead > 0);
fileToupload.Write(bytearray, 0, bytearray.Length);
fileToupload.Close();
fileToupload.Dispose();
return "success";
}
Please send links or code or any thing.
If you don't have idea about this please rank up this question..
thanks
public void checkinstream(String rid, String filename ) throws IOException
{
URL url=null;
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName= null;
existingFileName= "/mnt/sdcard/"+rid+".doc";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = Integer.MAX_VALUE;
String responseFromServer = "";
url = new URL("http://10.66.51.241/mywcf/Service.svc/Service/uploadMyDoc");
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
// 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", "application/stream");
dos = new DataOutputStream( conn.getOutputStream() );
// dos.writeBytes(twoHyphens + boundary + lineEnd);
//dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
// dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.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...
dos.writeBytes(lineEnd);
// close streams
Log.e("Debug",twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
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
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("Debug","Server Response "+str);
statuss.setText(str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
On the .net end create a wcf method which receives stream.
Thanks.

Categories

Resources