安卓httprul post方式上傳中文亂碼問題解決方案

    在使用httpurl post方式和服務器端jsp進行交互時,出現了寫入中文亂碼問題,且此時jdbc沒有問題,服務器端mysql已配置好utf-8碼制。此時可以確定問題是本地代碼中post請求寫入變量代碼存在問題。給出代碼作爲案例:

public void send() {  //獲取數據
		String target = "服務器端jsp地址"; // 要提交的目標地址
		URL url;
		try {
			url = new URL(target);
			HttpURLConnection urlConn = (HttpURLConnection) url
					.openConnection(); // 創建一個HTTP連接
			urlConn.setRequestMethod("POST"); // 指定使用POST請求方式
			urlConn.setDoInput(true); // 向連接中寫入數據
			urlConn.setDoOutput(true); // 從連接中讀取數據
			urlConn.setUseCaches(false); // 禁止緩存
			urlConn.setInstanceFollowRedirects(true); // 自動執行HTTP重定向
			urlConn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded"); // 設置內容類型
			DataOutputStream out = new DataOutputStream(
					urlConn.getOutputStream()); // 獲取輸出流
			String sql="SELECT  *  	FROM  course " 
					+ " where coursecademy	='"+ ac +"'and  coursedepartment	='"+de+"' "
					+"and coursename not in(select courseid from chooseinfo where userid='"+user+"');";
			//傳入學院  專業  和學生id
			Log.e("此處", ac);
			Log.e("此處", de);
			String param = "sql=" + URLEncoder.encode(sql, "utf-8"); // 連接所要提交的數據
			out.writeBytes(param);// 將要傳遞的數據寫入數據輸出流
			out.flush(); // 輸出緩存
			out.close(); // 關閉數據輸出流
			// 判斷是否響應成功
			if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStreamReader in = new InputStreamReader(
						urlConn.getInputStream()); // 獲得讀取的內容
				BufferedReader buffer = new BufferedReader(in); // 獲取輸入流對象
				String inputLine = null;
				strres = "";
				while ((inputLine = buffer.readLine()) != null) {
					strres += inputLine ;
				}
				in.close(); // 關閉字符輸入流
			}
			urlConn.disconnect(); // 斷開連接
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
    以上爲一個使用httpurl post方式進行信息發送的代碼,有詳細註釋,很容易看懂。

注意傳入的sql變量已經進行了utf-8編碼,此時傳入英文沒有問題,但傳入中文會出現亂碼。

    解決方法:將urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");改爲: urlConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded; charset=utf-8");  即可。

    特記下,以備後日回顧。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章