Android 网络应用--Apache HttpClient的使用
使用HttpClient发送请求,接收响应很简单,只要5步:
创建HttpClient 对象
创建HttpGet对象;或者是HttpPost 对象
如果需要发送请求参数,可以调用HttpGet HttpPost共同的setParams(HttpParams params) 方法来添加请求参数;对于HttpPost对象,也可以调用setEntity(HttpEntity entity)方法来设置请求参数
客户端条件参数: List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair ("LoginName", name)); params.add(new BasicNameValuePair ("LoginPassword", pass)); // 设置编码 post.setEntity(new UrlEncodedFormEntity( params, HTTP.UTF_8));
服务器端接收: String loginName = request.getParameter("LoginName"); String loginPassword = request.getParameter("LoginPassword");
4.调用HttpClient对象的excute()发送请求,返回一个HttpResponse 对象。
5.调用HttpResponse的getAllHeaders(),getHeaders()等方法可以获取服务器的响应头;调用HttpResponse的getEntity()可以获取HttpEntity对象,该对象包转了服务器的响应内容。
登录的实例:核心代码
服务器端用的servlet搭建
package LoginServlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AndroidLoginServler extends HttpServlet { private static final long serialVersionUID = 1L; public AndroidLoginServler() { super(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); System.out.println("doGet"); } // Url 地址 // http://localhost:8080/Android_Client/servlet/AndroidLoginServler?LoginName=yu&LoginPassword=123 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doPost"); request.setCharacterEncoding("UTF-8"); String loginName = request.getParameter("LoginName"); String loginPassword = request.getParameter("LoginPassword"); System.out.println(loginName); System.out.println(loginPassword); // 统一字符 避免乱码 response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = null; try { /* * 登录业务判断 */ out=response.getWriter(); if (loginName.equals("yu") && loginPassword.equals("123")) { // 登陆成功 out.print("success"); } else { // 登陆失败 out.print("failed"); } } finally { if (out != null) out.close(); } } }
客户端
package com.example.xiaocool.httpclienttest; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; 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 java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class MainActivity extends ActionBarActivity { TextView response; HttpClient httpClient; Handler handler = new Handler() { public void handleMessage(Message msg) { if (msg.what == 0x123) { response.append(msg.obj.toString() + "\n"); } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // 创建DefaultHttpClient对象 httpClient = new DefaultHttpClient(); response = (TextView) findViewById(R.id.response); } public void accessSecret(View v) { response.setText(""); new Thread() { @Override public void run() { // 创建HttpGet对象 HttpGet get = new HttpGet( "http://112.237.241.204:8080/Android_Client/servlet/AndroidLoginServler?LoginName=yu&LoginPassword=123"); try { // 发送get HttpResponse httpResponse = httpClient.execute(get); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { BufferedReader br = new BufferedReader( new InputStreamReader(entity.getContent())); String line = null; while ((line = br.readLine()) != null) { Message msg = new Message(); msg.what = 0x123; msg.obj = line; handler.sendMessage(msg); } } } catch (Exception e) { e.printStackTrace(); } } }.start(); } public void showLogin(View v) { //加载登陆界面 final View loginDialog = getLayoutInflater().inflate( R.layout.login, null); //使用对话框供用户登陆系统 new AlertDialog.Builder(MainActivity.this) .setTitle("登录系统") .setView(loginDialog) .setPositiveButton("登陆", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final String name = ((EditText) loginDialog .findViewById(R.id.name)).getText() .toString(); final String pass = ((EditText) loginDialog .findViewById(R.id.pass)).getText() .toString(); /*final String uri="http://112.237.241.204:8080/Android_Client/servlet/AndroidLoginServler?LoginName=" + name+"&LoginPassword="+pass;*/ final String uri="http://112.237.241.204:8080/Android_Client/servlet/AndroidLoginServler"; new Thread() { @Override public void run() { try { HttpPost post = new HttpPost(uri); /** * 定义了一个list,该list的数据类型是NameValuePair(简单名称值对节点类型, 这个代码多处用于Java像url发送Post请求。在发送post请求时用该list来存放参数 */ List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair ("LoginName", name)); params.add(new BasicNameValuePair ("LoginPassword", pass)); // 设置编码 post.setEntity(new UrlEncodedFormEntity( params, HTTP.UTF_8)); HttpResponse response = httpClient .execute(post); // 如果服务器成功返回响应 if (response.getStatusLine() .getStatusCode() == 200) { String msg = EntityUtils .toString(response.getEntity()); Looper.prepare(); //显示从服务器返回的信息 Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); Looper.loop(); } } catch (Exception e) { e.printStackTrace(); } } }.start(); } }).setNegativeButton("取消", null).show(); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。