Android,通过 HTTP POST (SOAP) 发送 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2559948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android, sending XML via HTTP POST (SOAP)
提问by JustFogMaxi
I would like to invoke a webservice via Android. I need to POST some XML to a URL via HTTP. I found this snipped for sending a POST, but i dont know how to include/add the XML data itself.
我想通过 Android 调用网络服务。我需要通过 HTTP 将一些 XML 发布到 URL。我发现这是为了发送 POST 而被截断的,但我不知道如何包含/添加 XML 数据本身。
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.10.4.35:53011/");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("Content-Type", "application/soap+xml"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Where/how to add the XML data?
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
This is the complete POST message that i need to imitate:
这是我需要模仿的完整 POST 消息:
POST /a8103e90-f1e3-11dd-bfdb-8b1fcff1a110 HTTP/1.1
Host: 10.10.4.35:53011
Content-Type: application/soap+xml
Content-Length: 602
<?xml version='1.0' encoding='UTF-8' ?>
<s12:Envelope xmlns:s12="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing">
<s12:Header>
<wsa:MessageID>urn:uuid:fc061d40-3d63-11df-bfba-62764ccc0e48</wsa:MessageID>
<wsa:Action>http://schemas.xmlsoap.org/ws/2004/09/transfer/Get</wsa:Action>
<wsa:To>urn:uuid:a8103e90-f1e3-11dd-bfdb-8b1fcff1a110</wsa:To>
<wsa:ReplyTo>
<wsa:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address>
</wsa:ReplyTo>
</s12:Header>
<s12:Body />
</s12:Envelope>
回答by Samuh
- First, you can create a String template for this SOAP request and substitute user-supplied values at runtime in this template to create a valid request.
- Wrap this string in a StringEntity and set its content type as text/xml
- Set this entity in the SOAP request.
- 首先,您可以为这个 SOAP 请求创建一个 String 模板,并在运行时在这个模板中替换用户提供的值来创建一个有效的请求。
- 将此字符串包装在 StringEntity 中并将其内容类型设置为 text/xml
- 在 SOAP 请求中设置此实体。
Something like:
就像是:
HttpPost httppost = new HttpPost(SERVICE_EPR);
StringEntity se = new StringEntity(SOAPRequestXML,HTTP.UTF_8);
se.setContentType("text/xml");
httppost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
httppost.setEntity(se);
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse =
(BasicHttpResponse) httpclient.execute(httppost);
response.put("HTTPStatus",httpResponse.getStatusLine().toString());
回答by HelmiB
here the alternative to send soap msg.
这里是发送肥皂味精的替代方法。
public String setSoapMsg(String targetURL, String urlParameters){
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
// for not trusted site (https)
// _FakeX509TrustManager.allowAllSSL();
// System.setProperty("javax.net.debug","all");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("SOAPAction", "**** SOAP ACTION VALUE HERE ****");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is ;
Log.i("response", "code="+connection.getResponseCode());
if(connection.getResponseCode()<=400){
is=connection.getInputStream();
}else{
/* error from server */
is = connection.getErrorStream();
}
// is= connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
Log.i("response", ""+response.toString());
return response.toString();
} catch (Exception e) {
Log.e("error https", "", e);
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
hope it helps. if anyone wonder allowAllSSL()
method, google it :).
希望能帮助到你。如果有人想知道allowAllSSL()
方法,请谷歌它:)。
回答by Maxrunner
So if you use:
所以如果你使用:
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
It is still rest, but if you use:
它仍然是休息,但如果你使用:
StringEntity se = new StringEntity(SOAPRequestXML,HTTP.UTF_8);
httppost.setEntity(se);
It is soap???
是肥皂???
回答by Jorgesys
Example sending XML to WS via http POST.
通过 http POST 将 XML 发送到 WS 的示例。
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://foo/service1.asmx/GetUID");
//XML example to send via Web Service.
StringBuilder sb = new StringBuilder();
sb.append("<myXML><Parametro><name>IdApp</name><value>1234567890</value></Parameter>");
sb.append("<Parameter><name>UID1</name><value>abc12421</value></Parameter>");
sb.append("</myXML>");
httppost.addHeader("Accept", "text/xml");
httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("myxml", sb.toString());//WS Parameter and Value
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
回答by PLG
Here's my code for sending HTML.... You can see the data is the nameValuePairs.add(...)
这是我发送 HTML 的代码......你可以看到数据是 nameValuePairs.add(...)
HttpClient httpclient = new DefaultHttpClient();
// Your URL
HttpPost httppost = new HttpPost("http://192.71.100.21:8000");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// Your DATA
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata","AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response;
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
回答by Nushio
I had to send some XML via HTTP Post on Android too.
我也必须通过 Android 上的 HTTP Post 发送一些 XML。
String xml = "xml-block";
StringEntity se = new StringEntity(xml,"UTF-8");
se.setContentType("application/atom+xml");
HttpPost postRequest = new HttpPost("http://some.url");
postRequest.setEntity(se);
Hope it works!
希望它有效!
回答by Anand Tiwari
here, the code snippets of code, that I am using for posting xml in SOAP services and in return getting Inputstream from web.
在这里,代码的代码片段,我用来在 SOAP 服务中发布 xml 并作为回报从 web 获取 Inputstream。
private InputStream call(String soapAction, String xml) throws IOException {
byte[] requestData = xml.getBytes("UTF-8");
URL url = new URL(URL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");
// connection.setRequestProperty("Accept-Encoding","gzip,deflate");
connection.setRequestProperty("Content-Type", "text/xml; UTF-8");
connection.setRequestProperty("SOAPAction", soapAction);
connection.setRequestProperty("User-Agent", "android");
connection.setRequestProperty("Host",
"base_urlforwebservices like - xyz.net");
// connection
// .setRequestProperty("Content-Length", "" + requestData.length);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
os = connection.getOutputStream();
os.write(requestData, 0, requestData.length);
os.flush();
os.close();
is = connection.getInputStream();
return is; // inputStream
}
Here xml: is the built xml request used to call services.
这里的 xml: 是用于调用服务的内置 xml 请求。
Have fun;
玩得开心;
回答by Ankur Choudhary
Another way of doing it is by using Apache Call. Api URL, Action URI and API Body needs to be provided
另一种方法是使用Apache Call。需要提供 Api URL、Action URI 和 API Body
InputStream input = new ByteArrayInputStream(apiBody.getBytes());
Service service = new Service();
Call call = (Call) service.createCall();
SOAPEnvelope soapEnvelope = new SOAPEnvelope(input);
call.setTargetEndpointAddress(new URL(apiUrl));
call.setUseSOAPAction(true);
if(StringUtils.isNotEmpty(actionURI)){
call.setSOAPActionURI(actionURI);
}
soapEnvelope = call.invoke(soapEnvelope);
return soapEnvelope.toString();