一、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
}