JavaWeb 发送post请求的2种方式(form、json)
CreationTime--2018年6月20日10点15分
Author:Marydon
前提:通过HttpClient来实现
方式一:以form表单形式提交数据
1.所需jar包
commons-logging-1.1.1.jar
httpclient-4.5.jar
httpcore-4.4.1.jar
2.代码实现
客户端如何发送请求?
导入
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils;
/** * 以form表单形式提交数据,发送post请求 * @explain * 1.请求头:httppost.setHeader("Content-Type","application/x-www-form-urlencoded") * 2.提交的数据格式:key1=value1&key2=value2... * @param url 请求地址 * @param paramsMap 具体数据 * @return 服务器返回数据 */ public static String httpPostWithForm(String url,Map<String, String> paramsMap){ // 用于接收返回的结果 String resultData =""; try { HttpPost post = new HttpPost(url); List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>(); // 迭代Map-->取出key,value放到BasicNameValuePair对象中-->添加到list中 for (String key : paramsMap.keySet()) { pairList.add(new BasicNameValuePair(key, paramsMap.get(key))); } UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(pairList, "utf-8"); post.setEntity(uefe); // 创建一个http客户端 CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 发送post请求 HttpResponse response = httpClient.execute(post); // 状态码为:200 if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ // 返回数据: resultData = EntityUtils.toString(response.getEntity(),"UTF-8"); }else{ throw new RuntimeException("接口连接失败!"); } } catch (Exception e) { throw new RuntimeException("接口连接失败!"); } return resultData; }
服务器端如何接收客户端传递的数据?
request.getParameter("key")
3.客户端调用测试
public static void main(String[] args) { String requestUrl = "http://localhost:8070/test/rz/server/rzxx/at_VaildToken.do"; Map<String, String> paramsMap = new HashMap<String, String>(1); paramsMap.put("un_value", "B022420184794C7C9D5096CC5F3AE7D2"); // 发送post请求并接收返回结果 String resultData = httpPostWithForm(requestUrl, paramsMap); System.out.println(resultData); }
方式二:以JSONObject形式提交数据
1.所需jar包
2.代码实现
客户端如何发送请求?
所需jar包:
commons-httpclient-3.0.jar
commons-codec-1.9.jar
commons-logging-1.1.1.jar
导入
import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity;
/** * 以json格式字符串形式提交数据,发送post请求 * @explain * 1.请求头:httppost.setHeader("Content-Type","application/json") * 2.提交的数据格式:"{"key1":"value1","key2":"value2",...}" * @param jsonStr * json字符串 * @return 服务器返回数据 */ public static String sendPostWithJson(String url, String jsonStr) { // 用于接收返回的结果 String jsonResult = ""; try { HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(3000); // //设置连接超时 client.getHttpConnectionManager().getParams().setSoTimeout(180000); // //设置读取数据超时 client.getParams().setContentCharset("UTF-8"); PostMethod postMethod = new PostMethod(url); postMethod.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); // 非空 if (null != jsonStr && !"".equals(jsonStr)) { StringRequestEntity requestEntity = new StringRequestEntity(jsonStr, "application/json", "UTF-8"); postMethod.setRequestEntity(requestEntity); } int status = client.executeMethod(postMethod); if (status == HttpStatus.SC_OK) { jsonResult = postMethod.getResponseBodyAsString(); } else { throw new RuntimeException("接口连接失败!"); } } catch (Exception e) { throw new RuntimeException("接口连接失败!"); } return jsonResult; }
服务器端如何接收客户端传递的数据?
所需jar包:
commons-beanutils-1.8.0.jar
commons-collections-3.2.1.jar
commons-lang-2.5.jar
commons-logging-1.1.1.jar
ezmorph-1.0.6.jar
json-lib-2.4-jdk15.jar
导入
import java.io.BufferedReader; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import net.sf.json.JSONObject;
/**
* 获取接口传递的JSON数据
* @explain
* @param request
* HttpServletRequest对象
* @return JSON格式数据
*/
public static JSONObject getJsonReqData(HttpServletRequest request) {
StringBuffer sb = new StringBuffer();
JSONObject jo = null;
BufferedReader reader = null;
try {
// json格式字符串
String jsonStr = "";
// 获取application/json格式数据,返回字符流
reader = request.getReader();
// 对字符流进行解析
while ((jsonStr = reader.readLine()) != null) {
sb.append(jsonStr);
}
} catch (IOException e) {
log.error("request请求解析失败:" + e.getMessage());
throw new RuntimeException("request请求解析失败:" + e.getMessage());
} finally {// 关闭流,避免一直占用该流资源,导致浪费
try {
if (null != reader) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
log.info("接收的参数信息为:{}" + sb.toString());
// 将json字符串(jsonStr)-->json对象(JSONObject)
try {
jo = JSONObject.fromObject(sb.toString());
} catch (Exception e) {
throw new RuntimeException("请求参数不是json格式数据!");
}
return jo;
}
3.客户端调用测试
public static void main(String[] args) { String requestUrl = "http://localhost:8070/test/rz/server/rzxx/at_VaildToken.do"; String jsonStr = "{\"un_value\":\"B022420184794C7C9D5096CC5F3AE7D2\"}"; // 发送post请求并接收返回结果 String resultData = sendPostWithJson(requestUrl, jsonStr); System.out.println(resultData); }
4.服务端接收测试
public static void main(String[] args) { //获取接口json数据 JSONObject jsonRequest = getJsonReqData(WebUtils.getRequest()); String s = jsonRequest.get("un_value").toString();// B022420184794C7C9D5096CC5F3AE7D2 // 或 s = jsonRequest.getString("un_value");// B022420184794C7C9D5096CC5F3AE7D2 }