前提:通过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 }
PS:20191211(合并版)
java作为客户端,去请求另一台服务器,数据格式完全可以以流的形式进行传送和接收,这样不管是form表单还是json都可以采用一种方式搞定。
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import org.apache.commons.lang3.StringUtils;
/** * java发送post请求(暂时只支持form表单提交和json数据提交两种方式,还可以根据需要自行扩展) * @expalin 说明: * form表单提交,要求参数格式必须是遵循form参数规范; * json数据提交,要求参数格式必须是遵循json标准规范。 * @param url * 服务器地址 * @param param * 请求参数 * 格式一:form表单形式,param1=value1¶m2=value2&... * 格式二:json数据形式,{"param1":"value1","param2":"value2",...} * @param contentType * 数据类型(暂时提供两种) * 格式一:form表单,application/x-www-form-urlencoded * 格式二:json数据,application/json * @param charset * 字符集 * 如果不传,默认值为:utf-8 */ public static String sendPostRequest(String url, String param, String contentType, String charset) { // 请求方法:post、get String requestMethod = "POST"; // 数据类型 if ("form".equals(contentType)) { contentType = "application/x-www-form-urlencoded"; } else if ("json".equals(contentType)) { contentType = "application/json"; } // 告诉请求数据的字符集 charset = "".equals(charset) ? "utf-8" : charset; // 用于接收服务器返回结果 StringBuffer responseResult = new StringBuffer(); HttpURLConnection conn = null; OutputStream out = null; BufferedReader reader = null; try { // 打开网址 URL requestUrl = new URL(url); conn = (HttpURLConnection) requestUrl.openConnection(); // 连接设置 conn.setRequestMethod(requestMethod); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); conn.setRequestProperty("Content-Type", contentType + ";" + charset); // 进行连接 conn.connect(); // 将数据以流的形式进行传输(二进制) out = conn.getOutputStream(); out.write(param.getBytes()); out.flush(); // 响应状态码:200-代表正常 int responseCode = conn.getResponseCode(); if (responseCode != 200) { throw new RuntimeException("Error responseCode:" + responseCode); } // 获取服务器响应数据字符集 String responseEncoding = conn.getContentEncoding(); responseEncoding = StringUtils.isEmpty(responseEncoding) ? "utf-8" : responseEncoding; // 读取服务器响应数据 String output = null; reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), responseEncoding)); while ((output = reader.readLine()) != null) { responseResult.append(output); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("调用接口出错:param=" + param); } finally { try { if (reader != null) { reader.close(); } if (out != null) { out.close(); } if (conn != null) { conn.disconnect(); } } catch (Exception e2) { e2.printStackTrace(); } } return responseResult.toString(); }
20200403
这样的话,接收数据的服务器不用再区分传过来的是form表单还是json,统一按照接收json那样以字符流的形式进行读取即可。
当然了,这还得和服务器协商好,不然你传过去的是二进制,它却还是按照request.getParameter(),服务器肯定接收不到。
另外,如果是浏览器按照application/x-www-form-urlencoded的编码格式向后台传递数据的话,服务器只能用request.getParameter()来接收,这才是规范用法。