溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java如何實(shí)現(xiàn)Post數(shù)據(jù)請求和接收

發(fā)布時(shí)間:2021-08-09 09:37:46 來源:億速云 閱讀:259 作者:小新 欄目:編程語言

這篇文章主要介紹Java如何實(shí)現(xiàn)Post數(shù)據(jù)請求和接收,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

這兩天在做http服務(wù)端請求操作,客戶端post數(shù)據(jù)到服務(wù)端后,服務(wù)端通過request.getParameter()進(jìn)行請求,無法讀取到數(shù)據(jù),搜索了一下發(fā)現(xiàn)是因?yàn)樵O(shè)置為text/plain模式才導(dǎo)致讀取不到數(shù)據(jù)

urlConn.setRequestProperty("Content-Type","text/plain; charset=utf-8");

若設(shè)置為以下方式,則通過request.getParameter()可以讀取到數(shù)據(jù)

urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

enctype的三種編碼

form表單中enctype屬性可以用來控制對表單數(shù)據(jù)的發(fā)送前的如何進(jìn)行編碼,即在發(fā)送到服務(wù)器之前,所有字符都會進(jìn)行編碼(空格轉(zhuǎn)換為"+"加號,特殊符號轉(zhuǎn)換為ASCIIHEX值)。默認(rèn)是application/x-www-form-urlencoded。

multipart/form-data用于發(fā)送二進(jìn)制的文件,其他兩種類型不能用于發(fā)送文件

text/plain用于發(fā)送純文本內(nèi)容,不對特殊字符進(jìn)行編碼,一般用于email之類的。

application/x-www-form-urlencoded和text/plain的區(qū)別簡單講就是一個(gè)發(fā)送html內(nèi)容,一個(gè)發(fā)送純文本內(nèi)容

application/x-www-form-urlencoded在發(fā)送前編碼所有字符(默認(rèn))

multipart/form-data不對字符編碼。在使用包含文件上傳控件的表單時(shí),必須使用該值。

text/plain空格轉(zhuǎn)換為"+"加號,但不對特殊字符編碼。

當(dāng)定義enctype為application/x-www-form-urlencoded時(shí),使用以下方式接收數(shù)據(jù)

request.getParameter(參數(shù)名);

當(dāng)定義enctype為text/plain時(shí),使用以下方式接收數(shù)據(jù)

// 接收請求數(shù)據(jù)
    BufferedReader reader = request.getReader();
    char[] buf = new char[512];
    int len = 0;
    StringBuffer contentBuffer = new StringBuffer();
    while ((len = reader.read(buf)) != -1) {
      contentBuffer.append(buf, 0, len);
    }
        String content = contentBuffer.toString();
        
        if(content == null){
            content = "";
        }

post與get

tp請求在所有的編程語言中幾乎都是支持的,我們常用的兩種為:GET,POST請求。一般情況下,發(fā)送一個(gè)GET請求都很簡單,因?yàn)閰?shù)直接放在請求的URL上,對于POST請求,由于其數(shù)據(jù)是在消息體中發(fā)送出去的,所以相對來說要麻煩一點(diǎn),再涉及到需要發(fā)送文件等二進(jìn)制的數(shù)據(jù)類型,就更需要更多的處理。

post和get可以通過鍵值對的方式進(jìn)行參數(shù)傳輸,服務(wù)端通過request.getparameter方式進(jìn)行請求獲取數(shù)據(jù)。

客戶端post數(shù)據(jù)到服務(wù)端,服務(wù)端接收處理

public class UrlConnection {
	@SuppressWarnings("finally") 
	  public static Boolean response(String url,String content) {
		String line     = "";
		String message    = "";
		String returnData  = "";
		Boolean postState   = false;
		BufferedReader bufferedReader = null;
		try {
			URL urlObject = new URL(url);
			HttpURLConnection urlConn = (HttpURLConnection) urlObject.openConnection();
			urlConn.setDoOutput(true);
			/*設(shè)定禁用緩存*/
			urlConn.setRequestProperty("Pragma:", "no-cache");
			urlConn.setRequestProperty("Cache-Control", "no-cache");
			/*維持長連接*/
			urlConn.setRequestProperty("Connection", "Keep-Alive");
			/*設(shè)置字符集*/
			urlConn.setRequestProperty("Charset", "UTF-8");
			/*設(shè)定輸出格式為json*/
			urlConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
			/*設(shè)置使用POST的方式發(fā)送*/
			urlConn.setRequestMethod("POST");
			/*設(shè)置不使用緩存*/
			urlConn.setUseCaches(false);
			/*設(shè)置容許輸出*/
			urlConn.setDoOutput(true);
			/*設(shè)置容許輸入*/
			urlConn.setDoInput(true);
			urlConn.connect();
			OutputStreamWriter outStreamWriter = new OutputStreamWriter(urlConn.getOutputStream(),"UTF-8");
			outStreamWriter.write(content);
			outStreamWriter.flush();
			outStreamWriter.close();
			/*若post失敗*/
			if((urlConn.getResponseCode() != 200)){
				returnData = "{\"jsonStrStatus\":0,\"processResults\":[]}";
				message = "發(fā)送POST失?。?quot;+ "code="+urlConn.getResponseCode() + "," + "失敗消息:"+ urlConn.getResponseMessage();
				// 定義BufferedReader輸入流來讀取URL的響應(yīng) 
				InputStream errorStream = urlConn.getErrorStream();
				if(errorStream != null) 
				        {
					InputStreamReader inputStreamReader = new InputStreamReader(errorStream,"utf-8");
					bufferedReader = new BufferedReader(inputStreamReader);
					while ((line = bufferedReader.readLine()) != null) {
						message += line;
					}
					inputStreamReader.close();
				}
				errorStream.close();
				System.out.println("發(fā)送失??!錯(cuò)誤信息為:"+message);
			} else{
				/*發(fā)送成功返回發(fā)送成功狀態(tài)*/
				postState = true;
				// 定義BufferedReader輸入流來讀取URL的響應(yīng) 
				InputStream inputStream = urlConn.getInputStream();
				InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");
				bufferedReader = new BufferedReader(inputStreamReader);
				while ((line = bufferedReader.readLine()) != null) {
					message += line;
				}
				returnData = message;
				inputStream.close();
				inputStreamReader.close();
				System.out.println("發(fā)送POST成功!返回內(nèi)容為:" + message);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			}
			catch (IOException ex) {
				ex.printStackTrace();
			}
			return postState;
		}
	}
	/*讀取request數(shù)據(jù)*/
	public static String getRequestData(HttpServletRequest request) throws IOException{
		BufferedReader reader = request.getReader();
		char[] buf = new char[512];
		int len = 0;
		StringBuffer contentBuffer = new StringBuffer();
		while ((len = reader.read(buf)) != -1) {
			contentBuffer.append(buf, 0, len);
		}
		String content = contentBuffer.toString();
		if(content == null){
			content = "";
		}
		return content;
	}
}

以上是“Java如何實(shí)現(xiàn)Post數(shù)據(jù)請求和接收”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI