main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/info" android:layout_width="fill_parent" android:layout_height="wrap_content"/> </LinearLayout>
MyWebDemo.java:
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.widget.TextView;
public class MyWebDemo extends Activity {
private static final String URL = "http://www.java123.cn/aaa/android.jsp" ;
private TextView info = null ; // 文本组件
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main); // 调用布局管理器
this.info = (TextView) super.findViewById(R.id.info); // 取得文本组件
boolean flag = false; // 判断标记
try {
HttpPost request = new HttpPost(URL); // 提交路径
List<NameValuePair> params = new ArrayList<NameValuePair>();// 设置提交参数
params.add(new BasicNameValuePair("id", "100")); // 设置id参数
params.add(new BasicNameValuePair("password", "111111"));// 设置password参数
request.setEntity(new UrlEncodedFormEntity(params,
HTTP.UTF_8)); // 设置编码
HttpResponse response = new DefaultHttpClient()
.execute(request); // 接收回应
if (response.getStatusLine().getStatusCode() != 404) { // 请求正常
flag = Boolean.parseBoolean(EntityUtils.toString(
response.getEntity()).trim()); // 接收返回的信息
}
} catch (Exception e) {
e.printStackTrace() ;
info.setText("WEB服务器连接失败。") ;
}
if (flag) { // 判断返回数据
info.setText("用户登陆成功!") ; // 设置文本
} else {
info.setText("用户登陆失败!") ; // 设置文本
}
}
}