客户端-服务器的简单交互

这里是之前的写过的Demo,参考了网上一些用法,自己又再发挥了一下,废话不多说,直接上代码!

这里以<用户名,密码> 登陆服务器为例!

1. 客户端 (这里介绍了请求服务器的三种一般用法)

package com.ville.client;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

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

public class Client {

	public static void main(String[] args) {
		login("ville", "123456");
	}
	/*
     * 通过用户名称和密码进行查询,发送Post请求,获得响应结果。
     */
    private static void login(String username,String password){
    	// 1. 使用 HttpURLConnection 实现
    	loginByHttpURLConnection(username, password);    	
    	// 2. 使用 HTTP Get
    	loginByHTTPGet(username, password);
    	// 3.使用HTTP Post
    	loginByHTTPPost(username, password);
       
    }
    
    /**
     *   1. 使用 HttpURLConnection 实现
     * */
    private static void loginByHttpURLConnection(String username,
			String password) {
		// TODO Auto-generated method stub
		
        String urlStr = "http://127.0.0.1:8080/Servlet/login?";
        String queryString = "username="+username+"&pwd="+password;
        urlStr+=queryString;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                
            if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
                InputStream in = conn.getInputStream();
                byte[] b = new byte[in.available()];
                in.read(b);
                String msg = new String(b);
                System.out.println("HttpURLConnection:"+msg+"");
                in.close();
            }else{
            	System.out.println("Connection Failed !");
            }
            conn.disconnect();
        } catch (Exception e) {
        	System.out.println("exception");
        }
	}
    
    /**
     * 2. 使用 Http post方式
     * */
	private static void loginByHTTPPost(String username, String password) {
		// TODO Auto-generated method stub
		 
	        String urlStr = "http://127.0.0.1:8080/Servlet/login";
	        HttpPost request = new HttpPost(urlStr);
	        // 如果传递参数个数比较多的话,我们可以对传递的参数进行封装
	        List<NameValuePair> params = new ArrayList<NameValuePair>();
	        params.add(new BasicNameValuePair("username", username));
	        params.add(new BasicNameValuePair("pwd", password));
	        try {
	            request.setEntity( new UrlEncodedFormEntity(params,HTTP.UTF_8));
	            HttpResponse response = new DefaultHttpClient().execute(request);
	            if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
	                String msg = EntityUtils.toString(response.getEntity());
	                System.out.println("HTTP Post: "+msg);
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	}
	
	/**
	 * 使用 Http get方式
	 * */
	private static void loginByHTTPGet(String username, String password) {
		// TODO Auto-generated method stub
		
		String urlStr = "http://127.0.0.1:8080/Servlet/login?";
        String queryString = "username="+username+"&pwd="+password;
        urlStr+=queryString;
        HttpGet request = new HttpGet(urlStr);
        try {
			HttpResponse response = new DefaultHttpClient().execute(request);
			if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
                String msg = EntityUtils.toString(response.getEntity());
                System.out.println("hTTP Get: "+msg);
            }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


2. 服务器端

package com.blues.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;

import com.blues.jdbc.User;
import com.blues.jdbc.UserDao;
import com.blues.jdbc.UserDaoImpl;
import com.google.gson.Gson;

public class LoginServlet extends HttpServlet{
	private Gson mJson = new Gson();
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("GBK");
		response.setCharacterEncoding("GBK");
		String name = request.getParameter("username");
		String password = request.getParameter("pwd");
		
		UserDao userDao = new UserDaoImpl();
		//此处为查询数据库操作,根据name, password来查找,有则返回user对象,无则返回null
		User user = userDao.login(name, password);
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String data = mJson.toJson(user);
		out.print(data);
		out.flush();
		out.close();
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
	
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值