使用Apache接口post方式传递数据

这篇博客是老罗视频学习笔记,详细介绍了如何使用Apache接口通过POST方式传递数据。在客户端,函数sendHttpClientPost和ChangeInputStream的实现与之前Java接口传递数据相似。测试代码也进行了展示。在服务器端,同样沿用之前的HTTP协议处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

老罗视频学习笔记。


一.客户端。


和上一篇java提供的接口传递数据基本类似。

sendHttpClientPost函数如下:

	private static String  sendHttpClientPost(String path,Map<String, String> params,String encode){
		//进行一下封装
		ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
		if(params!=null && !params.isEmpty()){
			for(Entry<String, String> entry : params.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 (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 encode;
		
	}

ChangeInputStream函数如下:和上一篇一样

private static String ChangeInputStream(InputStream inputStream,
			String encode) {
		// TODO Auto-generated method stub
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		String resultString = "";
		if(inputStream!=null) {
			try {
				//数据循环存储在outputStream中
				while ((len=inputStream.read(data))!=-1) {
					outputStream.write(data,0,len);
				}
				//首先转换为字节数组,然后以encode编码格式转换为字符串
				resultString = new String(outputStream.toByteArray(),encode);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return resultString;
	}


测试代码如下:

public static void main(String[] args) {
		// TODO Auto-generated method stub
		Map<String, String> params = new HashMap<String, String>();
		params.put("username", "admin");
		params.put("password", "123");
		
		String encode = "utf-8";
	
		String resString = httpUrils.sendHttpClientPost(path, params, encode);
		System.out.print("------>"+resString);
	}

二.服务器端

和上一篇的一样,这几篇http协议都用同一个服务器就可以






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值