在Android中向Web服务发送XML
我想将其作为XML发送到我的Web服务。我该怎么做在Android中向Web服务发送XML,android,web-services,android-ksoap2,Android,Web Services,Android Ksoap2,我想将其作为XML发送到我的Web服务。我该怎么做 <dmi:ShipNoticeRequest xmlns:dmi="http://portal.suppliesnet.net"> <dmi:RequesterISA>xxxxxxxxxx</dmi:RequesterISA> <dmi:ShipDateRange> <dmi:ShipDateFrom>2009-09-09</dmi: ShipDateFrom> <d
<dmi:ShipNoticeRequest xmlns:dmi="http://portal.suppliesnet.net">
<dmi:RequesterISA>xxxxxxxxxx</dmi:RequesterISA>
<dmi:ShipDateRange>
<dmi:ShipDateFrom>2009-09-09</dmi: ShipDateFrom>
<dmi:ShipDateTo>2009-09-10</dmi: ShipDateTo>
</dmi: ShipDateRange >
</dmi:ShipNoticeRequest>
您想要发送SOAP消息,而Android不直接支持发送此类消息。有类似KSOAP2 android的第三方库,您可以尝试使用。
服务器端的WSDL文件给出了每个SOAP消息的外观。尝试在服务器上找到它,并查看每个消息的外观。您可以使用soapUI为您解析WSDL文件。
如果您不使用上述任何第三方库,您必须自行编写该消息。您需要创建某种HTTP客户端,如下所示:
HttpURLConnection conn = null;
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/xml");
conn.setRequestProperty("Content-Length", "" + postMessageInBytes.length);
请求主体将使用例如XmlSerializer创建,它将帮助您编写所需的标记等。您可以使用KSOAP2访问web服务,并且您的XML数据可以轻松地作为字符串发送 1.下载文件 2.启动eclipse并创建新的android项目 3.右键单击您的项目 4.单击“属性” 5.单击左窗格中的java构建路径 6.选择“库”选项卡 7.单击Addexternaljar 8.浏览下载的jar文件 你的活动应该是这样的
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.*;
import android.util.Log;
import android.widget.TextView;
import android.os.Bundle;
public class FinalWebServiceDemoActivity extends Activity {
// some parameters regarding your web-service to be invoked
private static final String SOAP_ACTION = "http://tempuri.org/WebServiceMethod";
private static final String METHOD_NAME = "WebServiceMethod";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://10.0.2.2:2256/WebService.asmx";
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView)findViewById(R.id.text1);
call();
}
public void call()
{
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("message","Put your XML data here...");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
String strRes = result.toString();
tv.setText(strRes);
} catch (Exception e) {
tv.setText("Exception...");
Log.i("exception", e.toString());
StackTraceElement elements[] = e.getStackTrace();
for (int i = 0, n = elements.length; i < n; i++) {
Log.i("File", elements[i].getFileName());
Log.i("Line", String.valueOf(elements[i].getLineNumber()));
Log.i("Method", elements[i].getMethodName());
}
}
}
}
import org.ksoap2.SoapEnvelope;
导入org.ksoap2.serialization.SoapObject;
导入org.ksoap2.serialization.SoapPrimitive;
导入org.ksoap2.serialization.SoapSerializationEnvelope;
导入org.ksoap2.transport.HttpTransportSE;
导入android.app.*;
导入android.util.Log;
导入android.widget.TextView;
导入android.os.Bundle;
公共类FinalWebServiceDemoActivity扩展活动{
//有关要调用的web服务的一些参数
私有静态最终字符串SOAP_ACTION=”http://tempuri.org/WebServiceMethod";
私有静态最终字符串方法\u NAME=“WebServiceMethod”;
私有静态最终字符串命名空间=”http://tempuri.org/";
私有静态最终字符串URL=”http://10.0.2.2:2256/WebService.asmx";
文本视图电视;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView)findViewById(R.id.text1);
call();
}
公开作废通知()
{
试一试{
SoapObject请求=新的SoapObject(名称空间、方法名称);
addProperty(“消息”,“将XML数据放在这里…”);
SoapSerializationEnvelope=新的SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(请求);
HttpTransportSE androidHttpTransport=新的HttpTransportSE(URL);
调用(SOAP_操作,信封);
SoapPrimitive结果=(SoapPrimitive)信封.getResponse();
字符串strRes=result.toString();
tv.setText(stres);
}捕获(例外e){
tv.setText(“例外…”);
Log.i(“异常”,例如toString());
StackTraceElement元素[]=e.getStackTrace();
对于(inti=0,n=elements.length;i
不要忘记在清单文件中添加
权限
注意:此代码用于访问本地计算机上运行的.NETWeb服务,IPs用于访问Android Emulator。必要时对其进行修改
希望这有帮助…试试这个(纯Java标准):
package com.example.xmlfilecreator;
导入java.io.File;
导入java.io.FileNotFoundException;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.entity.mime.MultipartEntity;
导入org.apache.http.entity.mime.content.FileBody;
导入org.apache.http.entity.mime.content.StringBody;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.util.EntityUtils;
导入org.xmlpull.v1.XmlSerializer;
导入android.app.Activity;
导入android.os.Bundle;
导入android.os.Environment;
导入android.util.Log;
导入android.util.Xml;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.Button;
导入android.widget.TextView;
公共类XmlFileCreator扩展活动实现OnClickListener{
公共整数i=0;
按钮b3;
http实体再现性;
公共图文电视;
公共字符串filename=“”;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b3=(按钮)findViewById(R.id.upload);
tv=(TextView)findviewbyd(R.id.tv);
b3.setOnClickListener(本);
filename=“addupload.xml”;
字符串[]否=新字符串[]{
"1",
"2",
"3",
"4",
"5",
};
字符串[]questype=新字符串[]{
“类型1”,
“类型2”,
“第三类”,
“类型4”,
“第5类”,
};
字符串[]ques=新字符串[]{
"2+2",
"3+3",
"4+4",
"5+5",
"6+6",
};
字符串[]罐=新字符串[]{
"4",
"6",
"8",
"10",
"12",
};
字符串[]uans=新字符串[]{
"4",
"5",
"8",
"9",
HttpURLConnection conn = null;
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/xml");
conn.setRequestProperty("Content-Length", "" + postMessageInBytes.length);
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.*;
import android.util.Log;
import android.widget.TextView;
import android.os.Bundle;
public class FinalWebServiceDemoActivity extends Activity {
// some parameters regarding your web-service to be invoked
private static final String SOAP_ACTION = "http://tempuri.org/WebServiceMethod";
private static final String METHOD_NAME = "WebServiceMethod";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://10.0.2.2:2256/WebService.asmx";
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView)findViewById(R.id.text1);
call();
}
public void call()
{
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("message","Put your XML data here...");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
String strRes = result.toString();
tv.setText(strRes);
} catch (Exception e) {
tv.setText("Exception...");
Log.i("exception", e.toString());
StackTraceElement elements[] = e.getStackTrace();
for (int i = 0, n = elements.length; i < n; i++) {
Log.i("File", elements[i].getFileName());
Log.i("Line", String.valueOf(elements[i].getLineNumber()));
Log.i("Method", elements[i].getMethodName());
}
}
}
}
private WebServiceConnection(String xmlString) {
InputStream responseInputStream = null;
OutputStream requestOutputStream = null;
HttpURLConnection httpURLConnection = null;
try {
// Form the URL
URL url = new URL(URL_BASE + "?serviceId=3");
// Set the HTTP URL connection
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type", "text/html");
// Send request
requestOutputStream = httpURLConnection.getOutputStream();
requestOutputStream.write(xmlString.getBytes("UTF-8"));
// Receive response, then do anything with it
responseInputStream = httpURLConnection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch(SocketTimeoutException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
package com.example.xmlfilecreator;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlSerializer;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class XmlFileCreator extends Activity implements OnClickListener {
public int i=0;
Button b3;
HttpEntity resEntity;
public TextView tv;
public String filename="";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b3 = (Button)findViewById(R.id.upload);
tv = (TextView)findViewById(R.id.tv);
b3.setOnClickListener(this);
filename="addupload.xml";
String[] no = new String[] {
"1",
"2",
"3",
"4",
"5",
};
String[] questype = new String[] {
"type1",
"type2",
"type3",
"type4",
"type5",
};
String[] ques = new String[] {
"2+2",
"3+3",
"4+4",
"5+5",
"6+6",
};
String[] cans = new String[] {
"4",
"6",
"8",
"10",
"12",
};
String[] uans = new String[] {
"4",
"5",
"8",
"9",
"10",
};
//create a new file called "addupload.xml" in the SD card
File newxmlfile = new File(Environment.getExternalStorageDirectory()+"/"+filename);
try{
newxmlfile.createNewFile();
}catch(IOException e){
Log.e("IOException", "exception in createNewFile() method");
}
//we have to bind the new file with a FileOutputStream
FileOutputStream fileos = null;
try{
fileos = new FileOutputStream(newxmlfile);
}catch(FileNotFoundException e){
Log.e("FileNotFoundException", "can't create FileOutputStream");
}
//we create a XmlSerializer in order to write xml data
XmlSerializer serializer = Xml.newSerializer();
try {
//we set the FileOutputStream as output for the serializer, using UTF-8 encoding
serializer.setOutput(fileos, "UTF-8");
//Write <?xml declaration with encoding (if encoding not null) and standalone flag (if standalone not null)
serializer.startDocument(null, Boolean.valueOf(true));
//set indentation option
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
//start a tag called "root"
serializer.startTag(null, "Worksheet");
while(i<no.length)
{
//i indent code just to have a view similar to xml-tree
serializer.startTag(null, "Question");
//set an attribute called "attribute" with a "value" for <child2>
serializer.attribute(null, "number", no[i]);
serializer.endTag(null, "Question");
serializer.startTag(null, "QuestionType");
//write some text inside <child3>
serializer.text(questype[i]);
serializer.endTag(null, "QuestionType");
serializer.startTag(null, "Question");
serializer.text(ques[i]);
serializer.endTag(null, "Question");
serializer.startTag(null, "CorrectAnswer");
serializer.text(cans[i]);
serializer.endTag(null, "CorrectAnswer");
serializer.startTag(null, "UserAnswer");
serializer.text(uans[i]);
serializer.endTag(null, "UserAnswer");
i=i+1;
}
serializer.endTag(null, "Worksheet");
serializer.endDocument();
//write xml data into the FileOutputStream
serializer.flush();
//finally we close the file stream
fileos.close();
TextView tv = (TextView)this.findViewById(R.id.result);
tv.setText("file has been created on SD card");
} catch (Exception e) {
Log.e("Exception","error occurred while creating xml file");
}
}
public void onClick(View v)
{
if(v==b3)
{
// if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) && !(selectedPath2.trim().equalsIgnoreCase("NONE"))){
Thread thread=new Thread(new Runnable(){
public void run(){
doFileUpload();
runOnUiThread(new Runnable(){
public void run() {
tv.setText("uploaded successfully");
}
});
}
});
thread.start();
}
}
private void doFileUpload(){
File file1 = new File("/mnt/sdcard/"+filename);
File file2 = new File("/mnt/sdcard/mfqsheet.xml");
String urlString = "http://192.168.1.20:8080/NpTest/fileUpload";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
FileBody bin2 = new FileBody(file2);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
reqEntity.addPart("uploadedfile2", bin2);
reqEntity.addPart("user", new StringBody("User"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
// Toast.makeText(getApplicationContext(),"Upload <span id="IL_AD4" class="IL_AD">Complete</span>. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}
}