主界面一个访问页面按钮,一个登陆系统按钮,一个巨大的edittext,用来显示服务器的响应内容
如果没有登录,点击访问页面按钮会显示“您没有被授权访问该页面”。如果已经登陆,会在edittext中显示服务器的响应结果
发送请求的步骤:
1.创建HttpClient对象
2.如果发送GET请求,创建HttpGet对象,如果发送POST请求,创建HttpPost对象
3.调用HttpClient对象的execute()方法发送请求,执行该方法返回一个HttpResponse。
4.HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。
访问页面按钮的监听函数
HttpGet get = new HttpGet("http://222.18.174.132:8080/foo/secret.jsp");
try
{
//发送get请求
//httpClient对象的execute方法返回一个HttpResponse
HttpResponse httpResponse = httpClient.execute(get);
//httpResponse的getEntity方法获取的对象中,包装了服务器的响应内容
HttpEntity entity = httpResponse.getEntity();
if(entity != null)
{
//读取服务器响应
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
String line = null;
while((line = br.readLine())!= null)
{
//使用response文本框显示服务器响应
response.append(line + "\n");
}
}
}
登录系统按钮的监听函数
用getLayoutinflate.inflate方法得到我们要显示的xml文件,再用builder.setView方法将取出来的xml文件装载进对话框中
final View loginDialog = getLayoutInflater().inflate(R.layout.login, null);
new AlertDialog.Builder(httpclient.this)
.setTitle("登陆系统")
.setView(loginDialog)
.setPositiveButton("登陆", new DialogInterface.OnClickListener() {
//嵌套着登陆按钮的监听函数
public void onClick(DialogInterface arg0, int arg1) {
String name = ((EditText)loginDialog.findViewById(R.id.name)).getText().toString();
String pass = ((EditText)loginDialog.findViewById(R.id.pass)).getText().toString();
HttpPost post = new HttpPost("http://222.18.174.132:8080/foo/login.jsp");
//如果传递参数的个数比较多可以对传递的参数进行封装
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("pass", pass));
try
{
//设置请求参数
post.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//发送post请求
HttpResponse response = httpClient.execute(post);
//如果服务器成功的返回响应
if(response.getStatusLine().getStatusCode() == 200)
{
String msg = EntityUtils.toString(response.getEntity());
//提示登陆成功
Toast.makeText(httpclient.this, msg, 5000).show();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}).setNegativeButton("取消", null).show();
用户名是crazyit.org 密码是leegang
记得去注册访问网络的权限


代码