将xml文件发送到Android中的Web服务
作者:互联网
您好朋友,我正在尝试通过以下代码通过我的android应用发送存储在我的SD卡中的xml文件:
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文件的类型为:
<?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>
我不知道这段代码有什么问题,因为它无法正常工作并且文件无法上传.任何帮助将不胜感激.
解决方法:
您可以将其添加为NameValuePair
String xmlContent=getStringFromFile();//your method here
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("xmlData",
xmlContent));
并发送为
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.ISO_8859_1));
或者如果要发送为文件,则需要使用多部分
Ref Here:
标签:file,http-post,xml,android 来源: https://codeday.me/bug/20191029/1963826.html