前提:通過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()來接收,這才是規范用法。
