java模拟http请求带参数以及服务端接收

一、java发送post请求
public String sendPost(String url, Map<String, String> dataMap) {
		String result = "";
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		try {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("charset", "UTF-8"));// 压缩使用UTF-8
			if (dataMap != null && !dataMap.isEmpty()) {
				for (String key : dataMap.keySet()) {
					params.add(new BasicNameValuePair(key, dataMap.get(key)));
				}
			}
			httpPost.setEntity(new UrlEncodedFormEntity(params));
			HttpResponse response2 = httpclient.execute(httpPost);
			HttpEntity entity2 = response2.getEntity();
			result = EntityUtils.toString(entity2);
			EntityUtils.consume(entity2);
		} catch (UnsupportedEncodingException e) {

			e.printStackTrace();

		} catch (ClientProtocolException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			httpPost.releaseConnection();

		}
		return result;
	}

二、服务端接收参数并响应

/**
*接收HttpServletRequest传递过来的Map参数
*
*/
public static Map<String, String> getParamsMap(HttpServletRequest request)
{
		
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<?> fields = request.getParameterNames();
		
		while(fields.hasMoreElements())
		{
		String field = (String) fields.nextElement();
			String values[] = request.getParameterValues(field);
			if (values.length > 1)
				map.put(field, values.toString());
			else
				map.put(field, values[0]);
		
		}
		return map;
	}

**
*服务端处理
*/
public void serverPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		
		Map<String, String> payInfo = getParamsMap(request);
		
		//todo
		}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值