通過HttpClient請求webService
由于服務端是用webService開發的,android要調用webService服務獲取數據,這里采用的是通過HttpClient發送post請求,獲取webService數據。
服務端使用的webService框架是axis2,請求數據之前,要封裝一個xml格式,再通過post請求,獲取服務端數據。
請求的xml格式如下所示:
1 | < soap:Envelope xmlns:soap = "http://www.w3.org/2003/05/soap-envelope" xmlns:sam = "http://user.service.xxx.com" > |
5 | < sam:userName >sunlightcs</ sam:userName > |
其中:getUserInfo是方法名,userName是參數名,當然,還可以加多個參數。
下面的代碼是向webService發送請求,獲取數據,返回的數據是xml形式的,android只要解析xml數據,就可以獲得想要的數據了。
01 | import java.io.IOException; |
02 | import java.io.OutputStream; |
03 | import java.io.OutputStreamWriter; |
04 | import java.io.Writer; |
06 | import org.apache.http.HttpResponse; |
07 | import org.apache.http.client.HttpClient; |
08 | import org.apache.http.client.methods.HttpPost; |
09 | import org.apache.http.entity.ContentProducer; |
10 | import org.apache.http.entity.EntityTemplate; |
11 | import org.apache.http.impl.client.DefaultHttpClient; |
12 | import org.apache.http.util.EntityUtils; |
15 | public class ClientTest { |
17 | public static void main(String[] args) { |
18 | ClientTest.httpClientPost(); |
21 | private static void httpClientPost() { |
22 | HttpClient client = new DefaultHttpClient(); |
23 | HttpPost post = new HttpPost( "http://localhost:8080/xxx/services/userService" ); |
26 | ContentProducer cp = new ContentProducer() { |
27 | public void writeTo(OutputStream outstream) throws IOException { |
28 | Writer writer = new OutputStreamWriter(outstream, "UTF-8" ); |
33 | String requestXml = getRequestXml(); |
34 | writer.write(requestXml); |
39 | post.setEntity( new EntityTemplate(cp)); |
40 | HttpResponse response = client.execute(post); |
43 | System.out.println(EntityUtils.toString(response.getEntity())); |
44 | } catch (IOException e) { |
50 | private static String getRequestXml(){ |
51 | StringBuilder sb = new StringBuilder( "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:sam=\"http://user.service.xxx.com\">" ); |
52 | sb.append( "<soap:Header/>" ); |
53 | sb.append( "<soap:Body>" ); |
54 | sb.append( "<sam:getUserInfo>" ); |
55 | sb.append( "<sam:userName>sunlightcs</sam:userName>" ); |
56 | sb.append( "</sam:getUserInfo>" ); |
57 | sb.append( "</soap:Body>" ); |
58 | sb.append( "</soap:Envelope>" ); |
返回的數據格式如下:
1 | <? xml version = '1.0' encoding = 'UTF-8' ?> |
2 | < soapenv:Envelope xmlns:soapenv = "http://www.w3.org/2003/05/soap-envelope" > |
4 | < ns:getUserInfoResponse xmlns:ns = "http://user.service.xxx.com" > |
5 | < ns:return >xxx</ ns:return > |
6 | </ ns:getUserInfoResponse > |
其中,<ns:return>內的"xxx"可以是json數據,android只需解析標簽<ns:return>里的json數據即可。
轉載 http://www.juziku.com/wiki/3919.htm