我尝试将 Android 的 SOAP 查询请求发送到 w3schools 服务器,它将温度从摄氏度转换为华氏度,但我从服务器收到以下响应:
Server was unable to process request.
---> Data at the root level is invalid.
Line 1, position 1.
服务器在: http ://w3schools.com/webservices/tempconvert.asmx 。我们可以在以下网址找到 SOAP 请求消息结构:http ://w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit 。这是我的代码。
public class MainActivity extends Activity {
private static final String URL =
"http://www.w3schools.com/webservices/tempconvert.asmx";
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
StringBuffer sb = new StringBuffer("" +
"POST /webservices/tempconvert.asmx HTTP/1.1" +
"Host: w3schools.com" +
//"Content-Type: text/xml; charset=utf-8" +
//"Content-Length: length" +
"SOAPAction: \"http://tempuri.org/CelsiusToFahrenheit\"" +
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<CelsiusToFahrenheit xmlns=\"http://tempuri.org/\">" +
"<Celsius>24</Celsius>" +
"</CelsiusToFahrenheit>" +
"</soap:Body>" +
"</soap:Envelope>");
HttpPost request = new HttpPost(URL);
request.setHeader("Content-Type", "application/soap+xml; charset=utf-8");
tv = (TextView) findViewById(R.id.textView1);
try {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("myxml", sb.toString()));
request.setEntity(new UrlEncodedFormEntity(pairs));
response = httpclient.execute(request);
String response_string = EntityUtils.toString(response.getEntity());
//Here we should parse the response xml
//But for quicker way, we will display the whole response.
tv.setText("Temperature in Fahrenheit is: " + response_string);
Log.v("responseString", response_string)
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
如果你们能帮助我,我将不胜感激。谢谢!