UPDATE answer is here :) https://stackoverflow.com/a/23648537/6042879
i want to be able to upload my video and a variable to my server to use in the PHP script.
So far i can choose the video i want from my phone and upload it perfectly fine to the server but cant figure out exactly how to send the variable with the video. I can do them separately but it wont work if i combine them.
i use this code to use to upload variables:
//Uploads the product details
try {//Try block is to see if the call to the database can work.
URL url = new URL(ProductDetails_URL);//Create a new URL and put there variable "register_URL" into it.
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();//Create a httpConnection and open it
httpURLConnection.setRequestMethod("POST");//Use the request method
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("ProductOwnerEmail", "UTF-8") + "=" + URLEncoder.encode(ProductOwnerEmail, "UTF-8") + "&" +
URLEncoder.encode(DescriptionPoint3, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) { //url.openConnection() catch statement
e.printStackTrace();
}
Video upload code:
try{
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(UploadVideo_URL);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("myFile", selectedPath);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"myFile\";filename=\"" + selectedPath + "\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"Details\";Email=\"" + ProductOwnerEmail + "\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.write(ProductOwnerEmail.getBytes());
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"Details\";KeyCode=\"" + ProductKeyCode + "\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.write(ProductOwnerEmail.getBytes());
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
Log.i("Huzza", "Initial .available : " + bytesAvailable);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = conn.getResponseCode();
fileInputStream.close();
dos.flush();
dos.close();
} catch (Exception e) {
e.printStackTrace();
return "Product upload failed";
}
PHP code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$file_name = $_FILES['myFile']['name'];
$file_size = $_FILES['myFile']['size'];
$file_type = $_FILES['myFile']['type'];
$temp_name = $_FILES['myFile']['tmp_name'];
$ProductOwnerEmail = $_FILES['Details']['Email'];
$ProductKeyCode = $_FILES['Details']['KeyCode'];
$NewDirectory = "/var/www/html/ProductVideos/" . $ProductOwnerEmail;
if (!file_exists($NewDirectory))
{
mkdir($NewDirectory, 0777, true);
}
$location = "/var/www/html/ProductVideos/$ProductOwnerEmail/" . $ProductKeyCode;//$NewDirectory . '/' . $file_name;
move_uploaded_file($temp_name, $location);
echo "Uploaded!";
}else{
echo "Error";
}
?>
After you code:
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"myFile\";filename=\"" + SelectedPDF + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Write something like below to send variables:
dos.writeBytes(LINE_END);
// Loop a list of variable that you want to send to server.
/*for (StringKeyValuePair pair : yourVariableList) {
dos.writeBytes(TWO_HYPHENS + BOUNDARY + LINE_END);
dos.writeBytes("Content-Disposition: form-data; name=\"" + pair.getKey()+ "\"" + LINE_END);
dos.writeBytes(LINE_END);
dos.write(pair.getValue().getBytes());
dos.writeBytes(LINE_END);
}*/
dos.writeBytes(TWO_HYPHENS + BOUNDARY + LINE_END);
dos.writeBytes("Content-Disposition: form-data; name=\"ProductOwnerEmail\"" + LINE_END);
dos.writeBytes(LINE_END);
dos.write(ProductOwnerEmail.getBytes());
dos.writeBytes(LINE_END);
dos.writeBytes(TWO_HYPHENS + BOUNDARY + LINE_END);
dos.writeBytes("Content-Disposition: form-data; name=\"ProductKeyCode\"" + LINE_END);
dos.writeBytes(LINE_END);
dos.write(ProductKeyCode.getBytes());
dos.writeBytes(LINE_END);
U can use Volley lib for this purpose. It also Keep your requests in a queue and easy to use http://developer.android.com/training/volley/index.html
Related
I am using this for audio records and video file and it is working but i want to replace it with OkHttp. I didnt figure it out. Can anyone help me about it?
public class HttpMultipartUpload {
static String lineEnd = "\r\n";
static String twoHyphens = "--";
static String boundary = "AaB03x87yxdkjnxvi7";
public static String upload(URL url, File file, String fileParameterName, HashMap<String, String> parameters)
throws IOException {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream dis = null;
FileInputStream fileInputStream = null;
byte[] buffer;
int maxBufferSize = 20 * 1024;
try {
//------------------ CLIENT REQUEST
fileInputStream = new FileInputStream(file);
// open a URL connection to the Servlet
// 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("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"" + fileParameterName
+ "\"; filename=\"" + file.toString() + "\"" + lineEnd);
dos.writeBytes("Content-Type: text/xml" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
buffer = new byte[Math.min((int) file.length(), maxBufferSize)];
int length;
// read file and write it into form...
while ((length = fileInputStream.read(buffer)) != -1) {
dos.write(buffer, 0, length);
}
for (String name : parameters.keySet()) {
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(parameters.get(name));
}
// send multipart form data necessary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
} finally {
if (fileInputStream != null) fileInputStream.close();
if (dos != null) dos.close();
}
//------------------ read the SERVER RESPONSE
try {
dis = new DataInputStream(conn.getInputStream());
StringBuilder response = new StringBuilder();
String line;
while ((line = dis.readLine()) != null) {
response.append(line).append('\n');
}
return response.toString();
} finally {
if (dis != null) dis.close();
}
}
}
How can I change it with OkHttp. Any code please. I dont have good knowledge about on OkHttp. I was using (HttpURLConnection) but it seems not effective now.
See the documentation example on posting form data
https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/PostMultipart.java
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "Square Logo")
.addFormDataPart("image", "logo-square.png",
RequestBody.create(
new File("docs/images/logo-square.png"),
MEDIA_TYPE_PNG))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("https://api.imgur.com/3/image")
.post(requestBody)
.build();
I am recording audio and trying to upload audio on soundcloud server.but its not working can someone please correct me where i am doing wrong.I have searched alot but nothing works for me.I am a beginer in java.I already wasted 1 day on solving this problem.
private class AsyncTaskRunner extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... params) {
doFileUpload();
return null;
}
}
private void doFileUpload(){
HttpURLConnection conn = null;
//DataOutputStream dos = null;
//DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://api.soundcloud.com/tracks";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(AudioSavePathInDevice) );
// 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);
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
//Adding oauth token
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"oauth_token\""+lineEnd+lineEnd+access_token+lineEnd);
// dos.writeBytes(lineEnd);
//Adding Track title
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[title]\""+lineEnd+lineEnd+contributor_name+lineEnd);
// dos.writeBytes(lineEnd);
//Track taglist
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[tag_list]\""+lineEnd+lineEnd+"Tagore Project"+lineEnd);
// dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[asset_data]\";filename=\"" + AudioSavePathInDevice + "\"" + lineEnd);
// dos.writeBytes(lineEnd);
//Add sharing
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[sharing]\""+lineEnd+lineEnd+sharing+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);
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
Toast.makeText(this, ioe.getMessage(), Toast.LENGTH_SHORT).show();
}
//------------------ read the SERVER RESPONSE
// try {
// DataInputStream inStream = new DataInputStream ( conn.getInputStream() );
// String str;
// Log.e("Debug","Before while");
// while (( str = inStream.readLine()) != null)
// {
// Log.e("Debug","Server Response "+str);
// }
// inStream.close();
//
// }
try (InputStream is = conn.getInputStream()) {
BufferedReader lines = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// if(is == null) {
// Log.e("Debug","Reponse null ");
// }
// if(lines == null) {
// Log.e("Debug","Reponse null ");
// }
// int count = 0;
while (true) {
Log.e("Debug","Server Response ");
String line = lines.readLine();
if (line == null) {
Log.e("Debug","Server Break");
break;
}
}
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
and calling Asynctask like below on onClicklistener.
new AsyncTaskRunner().execute();
I'm using httpurlconnection for uploading files to different servers.
For some hosts the following code is working and I'm able to upload files, but when I'm trying to upload to another host, I get an error message
"failed to read: line too long: \nContent-Disposition: form-data; name...
What does this error mean? I couldn't find any hints with google. Hope you can help. :)
private void upload(){
response = "";
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "--------"+Long.toString(System.currentTimeMillis());
String lineEnd = "\n";
try {
File file = getFile();
StringBuffer sb = new StringBuffer();
sb.append(twoHyphens + boundary + lineEnd);
sb.append("Content-Disposition: form-data; name=\"file1\"; filename=\"" + getFilename() +"\"" + lineEnd);
sb.append("Content-Type: " + getMime() + lineEnd);
sb.append("Content-Transfer-Encoding: binary" + lineEnd);
sb.append(lineEnd);
FileInputStream fileInputStream = new FileInputStream(file);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setFixedLengthStreamingMode((uploadContainer.getFilesize() + sb.length() + lineEnd.length() + twoHyphens.length() + boundary.length() + twoHyphens.length() + lineEnd.length()));
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", USER_AGENT);
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=\"file1\"; filename=\"" + getFilename() +"\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + getMime() + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
int bytesRead = -1;
byte[] buffer = new byte[4096];
boolean cancelled = false;
while ((bytesRead = fileInputStream.read(buffer)) > 0){
outputStream.write(buffer, 0, bytesRead);
if(Thread.currentThread().isInterrupted()){
cancelled = true;
break;
}
}
if(cancelled == false){
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
outputStream.flush();
inputStream = connection.getInputStream();
response = convertStreamToString(inputStream);
inputStream.close();
} else {
// ...
}
fileInputStream.close();
} catch(Exception e) {/e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {e.printStackTrace();
}
}
}
String lineEnd = "\n";
The problem is here. The line terminator in HTTP is defined as \r\n, not \n.
I need to upload my file android device to server using webservice. But unfortunately Im getting error while doing it.Please help me to clear this error.
Here is my java code:
public class HttpFileUpload implements Runnable {
URL connectURL;
String responseString;
String Title;
String Description;
byte[ ] dataToServer;
FileInputStream fileInputStream = null;
HttpFileUpload(String urlString, String vTitle, String vDesc){
try{
connectURL = new URL(urlString);
Title= vTitle;
Description = vDesc;
}catch(Exception ex){
Log.i("HttpFileUpload","URL Malformatted");
}
}
void Send_Now(FileInputStream fStream){
fileInputStream = fStream;
Sending();
}
void Sending(){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String iFileName = "ovicam_temp_vid.mp4";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="fSnd";
try
{
Log.e(Tag,"Starting Http File Sending to URL");
// Open a HTTP connection to the URL
HttpURLConnection conn = (HttpURLConnection)connectURL.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);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Title);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Description);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag,"Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[ ] buffer = new byte[bufferSize];
// read file and write it into form...
int 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);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
fileInputStream.close();
dos.flush();
Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
String s=b.toString();
Log.i("Response",s);
dos.close();
}
catch (MalformedURLException ex)
{
Log.e(Tag, "URL error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
ioe.printStackTrace();
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
LogCat:
java.io.FileNotFoundException: http:///****8*******8/*****
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:210)
at arun.com.test.HttpFileUpload.Sending(HttpFileUpload.java:118)
at arun.com.test.HttpFileUpload.Send_Now(HttpFileUpload.java:36)
the average REST webservice won't return a response body on POST/PUT, just a response status. You'd like to determine it instead of the body.
Replace
InputStream response = conn.getInputStream();
by
int status = conn.getResponseCode();
All available status codes and their meaning are available in the HTTP spec, as linked before. The webservice itself should also come along with some documentation which overviews all status codes supported by the webservice and their special meaning, if any.
If the status starts with 4nn or 5nn, you'd like to use getErrorStream() instead to read the response body which may contain the error details.
InputStream error = con.getErrorStream();
Taken from this answer
I want to connect to a web-service and send a big file, i use HttpURLConnection like this:
private void doFileUpload() {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 8 * 1024 * 1024;
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(new File(getRealPathFromURI(fileUri)));
URL url = new URL("https://url.com/service.asmx?op=Method");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("SOAPAction", SOAP_ACTION);
conn.setRequestProperty("Host", "url.com");
conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + lineEnd);
dos.writeBytes("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/>"
+ lineEnd);
dos.writeBytes("<soap:Body>" + lineEnd);
dos.writeBytes("<IncluirMultimedia xmlns=/" + "www.url.es/>/" + lineEnd);
dos.writeBytes("<identificadorGUID>" + Guid + "<" + "/identificadorGUID>" + lineEnd);
dos.writeBytes("<numeroServicio>" + codigoServicio + "<" + "/numeroServicio>" + lineEnd);
dos.writeBytes("<contenido>" + ficheroAEnviar + "<" + "/contenido>" + lineEnd);
dos.writeBytes("<tipoMultimedia>" + "0" + "<" + "/tipoMultimedia>" + lineEnd);
dos.writeBytes("<coordenadaLatitud>" + "0.0" + "<" + "/coordenadaLatitud>" + lineEnd);
dos.writeBytes("<coordenadaLongitud>" + "0.0" + "<" + "/coordenadaLongitud>" + lineEnd);
dos.writeBytes("<extension>" + "mp4" + "<" + "/extension>" + lineEnd);
dos.writeBytes("<cuando>" + "0" + "<" + "/cuando>" + lineEnd);
dos.writeBytes("<IncluirMultimedia>" + lineEnd);
dos.writeBytes("</soap:Body>" + lineEnd);
dos.writeBytes("</soap:Envelope>");
buffer = new byte[8192];
bytesRead = 0;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
dos.write(buffer, 0, bytesRead);
}
BufferedReader r = new BufferedReader(new InputStreamReader(fileInputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
fileInputStream.close();
dos.flush();
dos.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
try {
conn.getContentLength();
if (conn.getResponseCode() >= 400) {
inStream = new DataInputStream(conn.getInputStream());
}
else {
inStream = new DataInputStream(conn.getErrorStream());
}
inStream.close();
}
catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
And my soap-request must be:
POST /url/url.asmx HTTP/1.1
Host: url.es
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "www.url.com/IncluirMultimedia"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<IncluirMultimedia xmlns="www.url.es">
<identificadorGUID>string</identificadorGUID>
<numeroServicio>string</numeroServicio>
<contenido>base64Binary</contenido>
<tipoMultimedia>int</tipoMultimedia>
<coordenadaLatitud>string</coordenadaLatitud>
<coordenadaLongitud>string</coordenadaLongitud>
<extension>string</extension>
<cuando>int</cuando>
</IncluirMultimedia>
</soap:Body>
</soap:Envelope>
I cant use ksoap2 because i need to send a very large file and this causes OutOfMemoryError. That's why i need to use this class.
I'm getting error 415, what am i doing wrong ?
Try using:
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
You are sending xml, I guess the server expects it.