用户在登录程序的时候,需要填写用户名和密码,用户名和密码要上传到服务器,如果用户名和密码正确,服务器会返回登录成功等信息。
那如何将用户名和密码发送到服务器端呢。下面简要的分四个步骤把主要代码分享出来。
1. 设置参数。就是把用户名和密码设置好。
List<NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username",username));
params.add(new BasicNameValuePair("password",password));
2.把设置好的参数绑定到Httppost对象上面。
HttpPost post=new HttpPost(urlpath);//urlpath 是你要发送请求的地址
post.setEntity(new UrlEncodedFormEntity(params,UTF-8));
3.生成HttpClient客户端对象,执行post请求得到HttpResponse对象
HttpClient client=new HttpClient();
HttpResponse response=client.execute(post);
4.通过HttpResponse对象得到输入流
if(response.getStatusLine().getStatusCode()==200){
String str=response.getEntity().getContent();}
好,到这发送用户名和密码请求的主要代码已经写完了。记住代码不要放到主线程中执行,
否则会报NetworkOnMainThreadException 异常