android http post调用webservice
那么接下来让我们看看在Android平台开发中如何执行一个Post请求:
以下是代码示例:
package com.jixuzou.search; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class mian extends Activity { /** Called when the activity is first created. */ private Button btnTest; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnTest = (Button) findViewById(R.id.Button01); btnTest.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getWeather(); } }); } private void getWeather(){ try { final String SERVER_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather"; // 定义需要获取的内容来源地址 HttpPost request = new HttpPost(SERVER_URL); // 根据内容来源地址创建一个Http请求 List params = new ArrayList(); params.add(new BasicNameValuePair("theCityCode", "长沙")); // 添加必须的参数 params.add(new BasicNameValuePair("theUserID", "")); // 添加必须的参数 request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // 设置参数的编码 HttpResponse httpResponse = new DefaultHttpClient().execute(request); // 发送请求并获取反馈 // 解析返回的内容 if (httpResponse.getStatusLine().getStatusCode() != 404) { String result = EntityUtils.toString(httpResponse.getEntity()); System.out.println(result); } } catch (Exception e) { } } }