步遥情感网
您的当前位置:首页通过HttpClient请求webService

通过HttpClient请求webService

来源:步遥情感网
通过HttpClient请求webService 通过HttpClient请求webService 由于服务端是用webService开发的,android要调用webService服务获取数据,这里采用的是通过HttpClient发送post请求,获取webService数据。 服务端使用的webService框架是axis2,请求数据之前,要封装一个xml格式,再通过post请求,获取服务端数据。 请求的xml格式如下所示: 1 3 4 5 6 7 8 下面的代码是向webService发送请求,获取数据,返回的数据是xml形式的,android只要解析xml数据,就可以获得想要的数据了。 sunlightcs 其中:getUserInfo是方法名,userName是参数名,当然,还可以加多个参数。 01 02 03 04 05 06 07 08 09 10 11 12 13 14 import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentProducer; import org.apache.http.entity.EntityTemplate; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; 15 16 17 18 19 20 21 22 public class ClientTest { public static void main(String[] args) { ClientTest.httpClientPost(); } private static void httpClientPost() { HttpClient client = new DefaultHttpClient(); 23 HttpPost post = newHttpPost(\"http://localhost:8080/xxx/services/24 25 26 try { ContentProducer cp = new ContentProducer() { 27 public void writeTo(OutputStream outstream) th28 Writer writer = new OutputStreamWriter(29 30 31 32 33 34 35 36 37 38 39 40 41 42 /** * 获取请求的xml格式数据 */ String requestXml = getRequestXml(); writer.write(requestXml); writer.flush(); } }; post.setEntity(new EntityTemplate(cp)); HttpResponse response = client.execute(post); //打印返回的xml数据 43 System.out.println(EntityUtils.toString(response.getEnti44 } catch (IOException e) { 45 46 e.printStackTrace(); } 47 48 49 50 } private static String getRequestXml(){ StringBuilder sb = new StringBuilder(\"\"); 52 sb.append(\"\"); 53 54 55 56 57 58 59 60 61 62 63 返回的数据格式如下: sb.append(\"\"); sb.append(\"\"); sb.append(\"sunlightcs\"); sb.append(\"\"); sb.append(\"\"); sb.append(\"\"); return sb.toString(); } 1 2 3 4 5 6 7 8 据即可。 转载 http://www.juziku.com/wiki/3919.htm xxx 其中,内的\"xxx\"可以是json数据,android只需解析标签里的json数

因篇幅问题不能全部显示,请点此查看更多更全内容