android:HttpClient请求(get、post)


本文主要介绍android如何通过HttpClient请求服务器端的内容

一:服务器端代码准备

     web.xml配置文件
    




    
      androidweb
    
    androidweb
     
      login
      com.smart.androidweb.servlet.LoginServlet
    
     
        login
        /login
    
    
        index.html
        index.xhtml
        index.htm
        index.jsp
    



  2.Servlet代码准备LoginServlet.java
package com.smart.androidweb.servlet;

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 LoginServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//在网上很有效的解决方法是添加:
		resp.setCharacterEncoding("UTF-8");
		//解决不了,后来又搜到一条解决方法是:
		resp.setHeader("content-type","text/html;charset=UTF-8");
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		
		PrintWriter writer = resp.getWriter();
		if("".equals(username) || username == null) {
			writer.print("用户名不能为空!");
			return ;
		}
		
		if("".equals(password) || password == null) {
			writer.print("密码不能为空");
			return ;
		}
		
		if("testname".equals(username) && "123456".equals(password)) {
			writer.print("登陆成功");
		} else {
			writer.print("登陆失败");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
	
//		resp.setreq
		doGet(req, resp);
		
	}
	
	
}

二:android端代码准备
    1)不要忘记在清单文件中添加网络访问权限
    
<uses-permission android:name="android.permission.INTERNET">uses-permission>
 
   
 2)android开发工具倒入一下两个jar包(没有的可以在网络上搜索下载一下)
httpclient-4.0.1.jar,httpcore-4.0.1.jar
 
   
 3)布局文件
activity_main.xml



    

        
            
            
        

        
            
            
        

        
            

4)java端代码
MainActivity.java
package com.smart.httpclient.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    EditText et_username;
    EditText et_password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_username = (EditText)findViewById(R.id.et_username);
        et_password = (EditText)findViewById(R.id.et_password);
    }

    public void onClick(View v) {
        if(v.getId() == R.id.bt_cannel) {
           loginPost();
        } else  if(v.getId() == R.id.bt_submit) {
            loginGet();
        }
    }
    /**
     * GET方式请求数据
     */
    public void loginGet() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String username = et_username.getText().toString().trim();
                String password = et_password.getText().toString().trim();
                //网络请求地址
                String urlPath = "http://192.168.1.6:8080/androidweb/login?username="+username+"&password="+password;
                //创建客户端请求对象
                DefaultHttpClient client = new DefaultHttpClient();
                //以GET的方式进行请求
                HttpGet get = new HttpGet(urlPath);
                try {
                    //获取服务器响应对象
                    HttpResponse response = client.execute(get);
                    //获取请求码200正确,404网址不存在,500服务器程序错误
                    int code = response.getStatusLine().getStatusCode();
                    if(code == 200) {
                       // 功过工具类把response的输出流转换成字符串
                        String content = EntityUtils.toString(response.getEntity(),"utf-8");
                        //显示获取的内容
                        showToast(content);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /**
     * Post方式请求数据,为安全起见都用post
     */
    public void loginPost() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String username = et_username.getText().toString().trim();
                String password = et_password.getText().toString().trim();
                //网络请求地址
                String urlPath = "http://192.168.1.6:8080/androidweb/login";//?username="+username+"&password="+password;
                //创建客户端请求对象
                DefaultHttpClient client = new DefaultHttpClient();
                //以Post的方式进行请求
                HttpPost post = new HttpPost(urlPath);
                //封装http求取参数
                List params = new ArrayList();
                NameValuePair pairun = new BasicNameValuePair("username",username);
                NameValuePair pairpw = new BasicNameValuePair("password",password);
                params.add(pairun);
                params.add(pairpw);
                try {
                    //组装请求内容
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
                    //设置请求参数
                    post.setEntity(entity);
                    //获取服务器响应对象
                    HttpResponse response = client.execute(post);
                    //获取请求码200正确,404网址不存在,500服务器程序错误
                    int code = response.getStatusLine().getStatusCode();
                    if(code == 200) {
                        // 功过工具类把response的输出流转换成字符串
                        String content = EntityUtils.toString(response.getEntity(),"utf-8");
                        //显示获取的内容
                        showToast(content);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /**
     * 封装吐司方法,使其在任意位置都可显示。
     * @param content
     */
    public void showToast(final String content) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(),content,Toast.LENGTH_LONG).show();
            }
        });
    }
}


 
  

你可能感兴趣的:(android,android网络处理)