博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用apache 提供的httpclient方式向服务器提交数据
阅读量:5863 次
发布时间:2019-06-19

本文共 3841 字,大约阅读时间需要 12 分钟。

hot3.png

1、客服端:

其中 utils.java代码如下:

package com.zwh.httpclient;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;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 Utils {	public Utils() {		// TODO Auto-generated constructor stub	}		/**	 * 	 * @param path	 * @param map	 * @param encode	 * @return	 */		public static String sendHttpClientPost(String path,			Map
map, String encode) { List
list=new ArrayList
(); for(Map.Entry
entry:map.entrySet()){ list.add(new BasicNameValuePair(entry.getKey(),entry.getValue())); } try { //实现将请求中的参数封装到请求参数中,请求体中 UrlEncodedFormEntity entity=new UrlEncodedFormEntity(list,encode); //使用post方式提交 HttpPost httpPost=new HttpPost(path); httpPost.setEntity(entity); //指定post方式提交数据 DefaultHttpClient client =new DefaultHttpClient(); HttpResponse httpResponse=client.execute(httpPost); if(httpResponse.getStatusLine().getStatusCode()==200){ return changeInputStream(httpResponse.getEntity().getContent(),encode); } } catch (Exception e) { // TODO: handle exception } return ""; } /** * * @param inputStream * @param encode * @return */ private static String changeInputStream(InputStream inputStream, String encode) { // TODO Auto-generated method stub ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int len = 0; byte[] date = new byte[1024]; String result = ""; try { while ((len = inputStream.read(date)) != -1) { outputStream.write(date, 0, len); } result = new String(outputStream.toByteArray(), encode); return result; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static void main(String[] args) { String path="http://localhost:8080/httppost/LoginServlet"; Map
params = new HashMap
(); params.put("username", "admin"); params.put("password", "123"); String result=Utils.sendHttpClientPost(path, params, "utf-8"); System.out.println(result); }}

2、服务器端代码如下:

package com.zwh.http;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 {	public void destroy() {		super.destroy(); // Just puts "destroy" string in log		// Put your code here	}	public void doGet(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		this.doPost(request,response);	}	public void doPost(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		response.setContentType("text/html;charset=utf-8");		response.setCharacterEncoding("utf-8");		request.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.println("login is success ! ");		}else{			out.println("login is failure ! ");					}				out.flush();		out.close();		}	public void init() throws ServletException {		// Put your code here	}}

客服端执行结果为:

login is success !

转载于:https://my.oschina.net/zhongwenhao/blog/137976

你可能感兴趣的文章
Android 平板中 自己定义键盘(popuwindow) 居于屏幕左下方 仿微信的password输入界面...
查看>>
Java的Executor框架和线程池实现原理(转)
查看>>
shader
查看>>
【javascript】九宫格抽奖组件设计
查看>>
python URLObject url处理模块
查看>>
Fiddler 抓包工具总结-bpafter
查看>>
Mac下docker搭建lamp本地开发环境
查看>>
Spark学习之路 (一)Spark初识
查看>>
建立组织级过程性能基线的注意事项
查看>>
python MQTT 出现TypeError: payload must be a string, bytearray, int, float or None.
查看>>
模型融合
查看>>
gcc编译选项【转】
查看>>
【spring boot】【mybatis】spring boot中mybatis打印sql语句
查看>>
Android App优化之ANR详解
查看>>
滴水不漏
查看>>
WPF控件深拷贝:序列化/反序列化
查看>>
Java的优先级任务队列的实践
查看>>
thinkphp5开发规范(加强复习之前的)
查看>>
Linux手工添加swap
查看>>
PowerTCP FTP for .NET 在线e文文档
查看>>