HttpClient之Post通信与服务器连接实现登陆功能

来源:互联网 发布:2015年各省地税数据 编辑:程序博客网 时间:2024/05/18 12:32

Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口,(基于Http协议的)即提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。

一、简介

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

下载地址: http://hc.apache.org/downloads.cgi

二、特性

1. 基于标准、纯净的java语言。实现了Http1.0和Http1.1

2. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。

3. 支持HTTPS协议。

4. 通过Http代理建立透明的连接。

5. 利用CONNECT方法通过Http代理建立隧道的https连接。

6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。

7. 插件式的自定义认证方案。

8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。

9. 连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。

10. 自动处理Set-Cookie中的Cookie。

11. 插件式的自定义Cookie策略。

12. Request的输出流可以避免流中内容直接缓冲socket服务器。

13. Response的输入流可以有效的从socket服务器直接读取相应内容。

14. 在http1.0和http1.1中利用KeepAlive保持持久连接。

15. 直接获取服务器发送的response code和 headers。

16. 设置连接超时的能力。

17. 实验性的支持http1.1 response caching。

18. 源代码基于Apache License 可免费获取。

三、使用方法

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

1. 创建HttpClient对象。

2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。

4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

6. 释放连接。无论执行方法是否成功,都必须释放连接


实例

main.xml(登陆界面,有点丑,不过没关系,功能实现就OK了)

<?xml version="1.0" encoding="utf-8"?><LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="@android:color/white"    android:orientation="vertical"  >    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content" >        <ImageView            android:id="@+id/login_head"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_gravity="center_horizontal"            android:layout_weight="1"            android:src="@drawable/nvren" />    </LinearLayout>    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_marginTop="20dp"        android:orientation="horizontal" >        <EditText            android:id="@+id/login_name"            android:layout_width="80dip"            android:layout_height="40dp"            android:layout_marginRight="15dp"            android:layout_marginTop="10dp"            android:layout_weight="0.90"            android:layout_marginLeft="20dip"            android:hint="请输入账号"            android:textSize="15sp" />    </LinearLayout>      <LinearLayout          android:layout_width="fill_parent"          android:layout_height="wrap_content"           android:layout_marginTop="10dp">          <EditText              android:id="@+id/login_Password"              android:layout_width="100dip"              android:layout_height="40dp"              android:layout_marginRight="15dp"              android:layout_weight="0.63"              android:layout_marginLeft="20dip"              android:ems="10"              android:hint="请输入密码"              android:lines="1"              android:password="true"              android:textSize="15sp" >                 </EditText>      </LinearLayout>      <LinearLayout           android:layout_width="fill_parent"           android:layout_height="wrap_content" >           <Button               android:id="@+id/btn_add_qrcode"               android:layout_width="80dp"               android:layout_height="50dp"               android:layout_gravity="center"               android:layout_marginTop="30dp"               android:layout_weight="0.92"               android:text="登陆"               android:textStyle="bold" />       </LinearLayout></LinearLayout>
效果如下:


MainActivity.java

package com.httpclient;import java.io.BufferedReader;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;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.json.JSONException;import org.json.JSONObject;import com.ericssonlabs.R;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.AutoCompleteTextView;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {private EditText et_uername;private EditText et_pwd;        private String Json_string;private JSONObject object;private static final String url = "http://www.quske.com:3003/login"; //服务端的url地址private HttpClient httpCilent;//创建一个HttpClient连接private HttpResponse response;////创建一个HttpResponse用于存放响应的数据private HttpPost httpPost;// //创建一个HttpPost请求private HttpEntity entity;//创建一个HttpEntity用于存放请求的实体数据   // Intent _intent=new Intent();        @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        et_uername = (EditText) this.findViewById(R.id.login_name);        et_pwd = (EditText) this.findViewById(R.id.login_Password);        Button generateQRCodeButton = (Button) this.findViewById(R.id.btn_add_qrcode);        generateQRCodeButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v){try {login(et_uername.getText().toString(),et_pwd.getText().toString());} catch (Exception e) {e.printStackTrace();} }});     }      public void login(String username,String password){            httpCilent = new DefaultHttpClient();  //实例化httpCilent        try{        httpPost = new HttpPost(url);//设置请求的路径        object=null;        object = new JSONObject();        try{        object.put("password",password.toString());   //object.put("ID",ID.toString());  object.put("username",username.toString());         }catch (JSONException e1) {                e1.printStackTrace();            }                List<NameValuePair> nvps = new ArrayList <NameValuePair>();         nvps.add(new BasicNameValuePair("username", username.toString()));          nvps.add(new BasicNameValuePair("password", password.toString()));                Json_string=null;Json_string=object.toString();httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); response = httpCilent.execute(httpPost); //执行请求获取响应     while(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){                //获取响应的实体数据                entity = response.getEntity();                StringBuffer sb = new StringBuffer();                // 通过reader读取实体对象包含的数据                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));                //循环读取实体里面的数据                String s = null;                while((s = reader.readLine()) != null){                    sb.append(s);                }        JSONObject datas = new JSONObject(sb.toString()); //创建一个JSONObject对象存放从服务端获取到的JSONObject数据        String result = datas.getString("status");//创建一个String变量用于存放服务端的处理结果状态            if(result.equals("success")){              Toast.makeText(this,datas.getString("msg") , Toast.LENGTH_SHORT).show();               }else{               Toast.makeText(this,datas.getString("msg") , Toast.LENGTH_SHORT).show();                  }            }      }catch(Exception e){       e.printStackTrace();      }    }}
如果出现以下问题

android.os.NetworkOnMainThreadException

请到这里求解

http://www.cnblogs.com/sjrhero/articles/2606833.html




0 0
原创粉丝点击