码迷,mamicode.com
首页 > Web开发 > 详细

通过Apache的httpClient的post方式连接服务器

时间:2015-05-21 09:05:06      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:apache   httpclient   post方式   



客户端的代码是:

package lgx.java.test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

public class HttpClientDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String path = "http://192.168.1.48:8080/myapp2/LoginAction";
		Map<String, String> params = new HashMap<String, String>();
		params.put("username", "admin");
		params.put("password", "123");
		String result =sendClientPostMessage(path, params, "utf-8");
		System.out.println("-->>"+result);
	}

	private static String sendClientPostMessage(String path,Map<String,String> param,String encode) {
		List<NameValuePair> list=new ArrayList<NameValuePair>();
		String result="";
		if(param!=null&&!param.isEmpty()){
			for(Map.Entry<String, String> entry:param.entrySet()){
				list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
		}
		
		try {
			//实现将请求的参数封装到表单中,请求体中
			UrlEncodedFormEntity entity=new UrlEncodedFormEntity(list, encode);
			//使用post提交数据
			HttpPost httpPost=new HttpPost(path);
			//设置使用的Entity
			httpPost.setEntity(entity);
			HttpClient client=new DefaultHttpClient();
			//客户端开始向指定的网址发送请求
			HttpResponse response=client.execute(httpPost);
			result= StreamToString(response.getEntity().getContent(),encode);
			
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 将一个输入流转换成指定编码的字符串
	 * 
	 * @param inputStream  输入流
	 * @param encode  编码格式
	 * @return  字符串
	 */
	private static String StreamToString(InputStream inputStream, String encode) {
		ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		String result = "";
		int len = 0;
		try {
			while ((len = inputStream.read(data)) != -1) {
				arrayOutputStream.write(data, 0, len);
			}
			result = new String(arrayOutputStream.toByteArray(), encode);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

}

服务端的代码是:

package com.login.manager;

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;

/**
 * Servlet implementation class LoginAction
 */
public class LoginAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public LoginAction() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out=response.getWriter();
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		System.out.println(username+"---->username");
		System.out.println(password+"----->password");
		
		if(username.equals("admin")&&password.equals("123")){
			out.print("longin is success");
		}else{
			out.print("login is failed");
		}
	}

}

客户端的控制台:


-->>longin is success

服务端的控制台:


admin---->username
123----->password


通过Apache的httpClient的post方式连接服务器

标签:apache   httpclient   post方式   

原文地址:http://blog.csdn.net/harryweasley/article/details/45887003

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!