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

一、java发送post请求
public String sendPost(String url, Map dataMap) {
		String result = "";
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		try {
			List params = new ArrayList();
			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 getParamsMap(HttpServletRequest request)
{
		
		Map map = new HashMap();
		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 payInfo = getParamsMap(request);
		
		//todo
		}



你可能感兴趣的:(java)