Reputation: 1632
Hello Friends I am trying to send an xml file stored in my sd card through my android app with the piece of code below:
public class CartDetailsActivity extends Activity {
File newxmlfile = new File(Environment.getExternalStorageDirectory() + "/"+GlobalVariables.ada_login+".xml");
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.cart_details);
Button payButton=(Button)findViewById(R.id.pay);
payButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new PostXmlClass().execute();
}
});
}
public class PostXmlClass extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(
CartDetailsActivity.this);
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
this.dialog.show();
}
@Override
protected Void doInBackground(Void... params) {
String url = "http://mywebsite.com/myfolder/mypage.php";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(newxmlfile), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...
} catch (Exception e) {
// show error
} // inside the method paste your file uploading code
return null;
}
protected void onPostExecute(Void result) {
// Here if you wish to do future process for ex. move to another activity do here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
}
xml file is of the type:
<?xml version='1.0' standalone='yes' ?>
<root>
<item>
<code>ACT358</code>
<price>110.00</price>
<quantity>3</quantity>
<totalcost>330.0</totalcost>
</item>
<item>
<code>ACT443</code>
<price>110.00</price>
<quantity>2</quantity>
<totalcost>220.0</totalcost>
</item>
</root>
I don't know whats wrong with this code as it is not working and file does not get uploaded. Any help will be appreciated.
Upvotes: 3
Views: 3260
Reputation: 1518
I Tweaked your doInBackground to how i do the exact same thing: Give it a try:
@Override
protected Void doInBackground(Void... params) {
String url = "http://mywebsite.com/myfolder/mypage.php";
try {
FileReader fr = new FileReader(newxmlfile);
BufferedReader br = new BufferedReader(fr);
StringBuffer sb = new StringBuffer();
String line = "";
while((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
br.close();
fr.close();
String xml = sb.toString();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
StringEntity se = new StringEntity(xml);
se.setContentType("text/xml");
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...
} catch (Exception e) {
// show error
} // inside the method paste your file uploading code
return null;
}
I wrote a dictionary tutorial while back where i send xml to web service, Have a look at it here for more info Andorid Dictionary Tutorial
Upvotes: 0
Reputation: 5234
Try below code, hope this gonna help you.
PHP web-service
<?php
// Where the file is going to be placed
$target_path = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$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!";
echo "filename: " . basename( $_FILES['uploadedfile']['name']);
echo "target_path: " .$target_path;
}
?>
Java Code
String path = Environment.getExternalStorageDirectory() + "/"+GlobalVariables.ada_login+".xml"";
new uploadFiletoServer().execute(path);
and here is your uploadFile
class uploadFiletoServer extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(yourActivity.this);
pDialog.setMessage("Uploading file to server. Please wait ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@SuppressWarnings("deprecation")
@Override
protected String doInBackground(String... arg0) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = path;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024 * 1024;
String urlString = url;
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);
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);
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);
}
return null;
}
protected void onPostExecute(String file_url) {
if (pDialog.isShowing()) {
pDialog.dismiss();
}
}
}
Upvotes: 0
Reputation: 191
Try this code, it works fine for me:
//Creating xml file
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
dbfac.setNamespaceAware(true);
DocumentBuilder docBuilder = null;
try {
docBuilder = dbfac.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DOMImplementation domImpl = docBuilder.getDOMImplementation();
Document document = domImpl.createDocument("http://coggl.com/InsertTrack","TrackEntry", null);
document.setXmlVersion("1.0");
document.setXmlStandalone(true);
Element trackElement = document.getDocumentElement();
Element CompanyId = document.createElement("CompanyId");
CompanyId.appendChild(document.createTextNode("1"));
trackElement.appendChild(CompanyId);
Element CreatedBy = document.createElement("CreatedBy");
CreatedBy.appendChild(document.createTextNode("6"));
trackElement.appendChild(CreatedBy);
Element DepartmentId = document.createElement("DepartmentId");
DepartmentId.appendChild(document.createTextNode("4"));
trackElement.appendChild(DepartmentId);
Element IsBillable = document.createElement("IsBillable");
IsBillable.appendChild(document.createTextNode("1"));
trackElement.appendChild(IsBillable);
Element ProjectId = document.createElement("ProjectId");
ProjectId.appendChild(document.createTextNode("1"));
trackElement.appendChild(ProjectId);
Element StartTime = document.createElement("StartTime");
StartTime.appendChild(document.createTextNode("2012-03-14 10:44:45"));
trackElement.appendChild(StartTime);
Element StopTime = document.createElement("StopTime");
StopTime.appendChild(document.createTextNode("2012-03-14 11:44:45"));
trackElement.appendChild(StopTime);
Element TaskId = document.createElement("TaskId");
TaskId.appendChild(document.createTextNode("3"));
trackElement.appendChild(TaskId);
Element TotalTime = document.createElement("TotalTime");
TotalTime.appendChild(document.createTextNode("1"));
trackElement.appendChild(TotalTime);
Element TrackDesc = document.createElement("TrackDesc");
TrackDesc.appendChild(document.createTextNode("testing"));
trackElement.appendChild(TrackDesc);
Element TrackId = document.createElement("TrackId");
TrackId.appendChild(document.createTextNode("0"));
trackElement.appendChild(TrackId);
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = null;
try {
trans = transfac.newTransformer();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
try {
trans.transform(source, result);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String xmlString = sw.toString();
//posting xml file to server
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.19:3334/cogglrestservice.svc/InsertTrack");
// Make sure the server knows what kind of a response we will accept
httppost.addHeader("Accept", "text/xml");
// Also be sure to tell the server what kind of content we are sending
httppost.addHeader("Content-Type", "application/xml");
try
{
StringEntity entity = new StringEntity(xmlString, "UTF-8");
entity.setContentType("application/xml");
httppost.setEntity(entity);
// execute is a blocking call, it's best to call this code in a thread separate from the ui's
HttpResponse response = httpClient.execute(httppost);
BasicResponseHandler responseHandler = new BasicResponseHandler();
String strResponse = null;
if (response != null) {
try {
strResponse = responseHandler.handleResponse(response);
} catch (HttpResponseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.e("WCFTEST", "WCFTEST ********** Response" + strResponse);
}
catch (Exception ex)
{
ex.printStackTrace();
}
Toast.makeText(EditTask.this, "Xml posted succesfully.",Toast.LENGTH_SHORT).show();
From Sent Xml file
Upvotes: 1
Reputation: 2562
I hope it will work
// the file to be posted
String textFile = Environment.getExternalStorageDirectory() + "/sample.txt";
Log.v(TAG, "textFile: " + textFile);
// the URL where the file will be posted
String postReceiverUrl = "http://yourdomain.com/post_data_receiver.php";
Log.v(TAG, "postURL: " + postReceiverUrl);
// new HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
File file = new File(textFile);
FileBody fileBody = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", fileBody);
httpPost.setEntity(reqEntity);
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v(TAG, "Response: " + responseStr);
// you can add an if statement here and do other actions based on the response
}
and php code.
<?php
// if text data was posted
if($_POST){
print_r($_POST);
}
// if a file was posted
else if($_FILES){
$file = $_FILES['file'];
$fileContents = file_get_contents($file["tmp_name"]);
print_r($fileContents);
}
?>
Upvotes: 1
Reputation: 25287
Try this code:
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
}
For more details, refer: http://reecon.wordpress.com/2010/04/25/uploading-files-to-http-server-using-post-android-sdk/
These are the additional links if the above didn't work:
--> http://www.tecnojin.it/wordpress/?p=194
--> http://vikaskanani.wordpress.com/2011/01/11/android-upload-image-or-file-using-http-post-multi-part/
--> http://www.anddev.org/upload_files_to_web_server-t443-s15.html
Upvotes: 1
Reputation: 20041
you can add this as NameValuePair
String xmlContent=getStringFromFile();//your method here
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("xmlData",
xmlContent));
and send as
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.ISO_8859_1));
OR If you want to send as a file you need to use the multi-part Ref Here:
Upvotes: 1