在android中向web服务发送xml文件
朋友们好,我正在尝试通过android应用程序发送存储在sd卡中的xml文件,代码如下:在android中向web服务发送xml文件,android,xml,file,http-post,Android,Xml,File,Http Post,朋友们好,我正在尝试通过android应用程序发送存储在sd卡中的xml文件,代码如下: public class CartDetailsActivity extends Activity { File newxmlfile = new File(Environment.getExternalStorageDirectory() + "/"+GlobalVariables.ada_login+".xml"); @Override protected void o
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();
}
}
}
}
我不知道这段代码有什么问题,因为它不工作,文件也没有上传。任何帮助都将不胜感激 您可以将其添加为
NameValuePair
String xmlContent=getStringFromFile();//your method here
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("xmlData",
xmlContent));
或者,如果要作为文件发送,则需要使用“多部分”
请尝试以下代码:
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
}
有关更多详细信息,请参阅:
如果上述操作不起作用,以下是附加链接:
-->
-->
-->我希望它能起作用
// 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);
}
?>
//要发布的文件
字符串textFile=Environment.getExternalStorageDirectory()+“/sample.txt”;
Log.v(标记“textFile:+textFile”);
//将发布文件的URL
字符串postReceiverUrl=”http://yourdomain.com/post_data_receiver.php";
Log.v(标签“postURL:+postReceiverUrl”);
//新的HttpClient
HttpClient HttpClient=新的DefaultHttpClient();
//柱头
HttpPost HttpPost=新的HttpPost(postReceiverUrl);
文件文件=新文件(textFile);
FileBody FileBody=新的FileBody(文件);
MultipartEntity reqEntity=新的MultipartEntity(HttpMultipartMode.BROWSER_兼容);
reqEntity.addPart(“文件”,文件体);
httpPost.setEntity(reqEntity);
//执行HTTP post请求
HttpResponse response=httpClient.execute(httpPost);
HttpEntity当前性=response.getEntity();
if(最近性!=null){
String responsest=EntityUtils.toString(resEntity.trim();
Log.v(标签,“响应:+responsest”);
//您可以在此处添加if语句,并根据响应执行其他操作
}
和php代码。
从尝试下面的代码,希望这对您有所帮助 PHP web服务
<?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;
}
?>
String path = Environment.getExternalStorageDirectory() + "/"+GlobalVariables.ada_login+".xml"";
new uploadFiletoServer().execute(path);
这是你的上传文件
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();
}
}
}
类uploadFiletoServer扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=newprogressdialog(yourActivity.this);
setMessage(“正在将文件上载到服务器。请稍候…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(假);
pDialog.show();
}
@抑制警告(“弃用”)
@凌驾
受保护的字符串doInBackground(字符串…arg0){
HttpURLConnection conn=null;
DataOutputStream dos=null;
DataInputStream inStream=null;
字符串existingFileName=路径;
String lineEnd=“\r\n”;
字符串双连字符=“--”;
字符串边界=“*******”;
int字节读取,字节可用,缓冲区大小;
字节[]缓冲区;
int maxBufferSize=1*1024*1024*1024;
字符串urlString=url;
试一试{
//--------------客户端请求
FileInputStream FileInputStream=新文件inputstream(新文件(
现有文件名);
//打开到Servlet的URL连接
URL=新URL(URL字符串);
//打开到URL的HTTP连接
conn=(HttpURLConnection)url.openConnection();
//允许输入
conn.setDoInput(真);
//允许输出
连接设置输出(真);
//不要使用缓存副本。
conn.SETUSECHACHES(假);
//使用post方法。
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“连接”、“保持活动”);
conn.setRequestProperty(“内容类型”,
“多部分/表单数据;边界=”+边界);
dos=新的DataOutputStream(conn.getOutputStream());
写字节(两个连字符+边界+行结束);
dos.writeBytes(“内容处置:表单数据;名称=\“uploadedfile\”文件名=\”
+现有文件名+“\”+lineEnd);
dos.writeBytes(lineEnd);
//创建最大大小的缓冲区
bytesAvailable=fileInputStream.available();
bufferSize=Math.min(字节可用,maxBufferSize);
buffer=新字节[bufferSize];
//读取文件并将其写入表单。。。
bytesRead=fileInputStream.read(缓冲区,0,缓冲区大小);
而(字节读取>0){
写入(缓冲区,0,缓冲区大小);
bytesAvailable=fileInputStream.available();
bufferSize=Math.min(字节可用,maxBufferSize);
bytesRead=fileInputStream.read(缓冲区,0,缓冲区大小);
}
//发送文件数据后所需的多部分表单数据。。。
dos.writeBytes(lineEnd);
写字节(两个连字符+边界+两个连字符+行结束);
//合流
Log.e(“调试”,“文件已写入”);
fileInputStream.close();
dos.flush();
dos.close();
}捕获(格式错误){
Log.e(“调试”,“错误:”+ex.getMessage(),ex);
}捕获(ioe异常ioe){
Log.e(“调试”,“错误:”+ioe.getMessage(),ioe);
}
//--------------读取服务器响应
试一试{
inStream=新数据输入流(conn.getInputStream());
字符串str;
while((str=inStream.readLine())!=null){
Log.e(“调试”、“服务器响应”+str);
}
流内关闭();
}捕获(IOException ioex){
Log.e(“调试”,“错误:”+ioex.getMessage(),ioex);
}
返回null;
}
受保护的void onPostExecute(字符串文件\u url){
if(pDialog.isShowing()){
pDialog.disclose();
}
}
}
I调整
<?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;
}
?>
String path = Environment.getExternalStorageDirectory() + "/"+GlobalVariables.ada_login+".xml"";
new uploadFiletoServer().execute(path);
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();
}
}
}
@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;
}