生活随笔
收集整理的這篇文章主要介紹了
URL特殊字符转码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
什么是URL轉碼
不管是以何種方式傳遞url時,如果要傳遞的url中包含特殊字符,如想要傳遞一個+,但是這個+會被url會被編碼成空格,想要傳遞&,被url處理成分隔符。
尤其是當傳遞的url是經過Base64加密或者RSA加密后的,存在特殊字符時,這里的特殊字符一旦被url處理,就不是原先你加密的結果了。
url特殊符號及對應的編碼:
| 符號 | url中的含義 | 編碼 |
| + | URL 中+號表示空格 | %2B |
| 空格 | URL中的空格可以用+號或者編碼 | %20 |
| / | 分隔目錄和子目錄 | %2F |
| ? ? ? ? ? ? ? ? | 分隔實際的URL和參數 | %3F |
| % | 指定特殊字符 | %25 |
| # | 表示書簽 | %23 |
| & | URL中指定的參數間的分隔符 | %26 |
| = | URL中指定參數的值 | %3D |
package com.learn.utils;import java.io.IOException;import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import com.alibaba.fastjson.JSONObject;/*** HttpClient4.3工具類*/
public class HttpClientUtils {private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class); // 日志記錄private static RequestConfig requestConfig = null;static {// 設置請求和傳輸超時時間requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();}/*** post請求傳輸json參數* * @param url* url地址* @param json* 參數* @return*/public static JSONObject httpPost(String url, JSONObject jsonParam) {// post請求返回結果CloseableHttpClient httpClient = HttpClients.createDefault();JSONObject jsonResult = null;HttpPost httpPost = new HttpPost(url);// 設置請求和傳輸超時時間httpPost.setConfig(requestConfig);try {if (null != jsonParam) {// 解決中文亂碼問題StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");entity.setContentEncoding("UTF-8");entity.setContentType("application/json");httpPost.setEntity(entity);}CloseableHttpResponse result = httpClient.execute(httpPost);// 請求發送成功,并得到響應if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {String str = "";try {// 讀取服務器返回過來的json字符串數據str = EntityUtils.toString(result.getEntity(), "utf-8");// 把json字符串轉換成json對象jsonResult = JSONObject.parseObject(str);} catch (Exception e) {logger.error("post請求提交失敗:" + url, e);}}} catch (IOException e) {logger.error("post請求提交失敗:" + url, e);} finally {httpPost.releaseConnection();}return jsonResult;}/*** post請求傳輸String參數 例如:name=Jack&sex=1&type=2* Content-type:application/x-www-form-urlencoded* * @param url* url地址* @param strParam* 參數* @return*/public static JSONObject httpPost(String url, String strParam) {// post請求返回結果CloseableHttpClient httpClient = HttpClients.createDefault();JSONObject jsonResult = null;HttpPost httpPost = new HttpPost(url);httpPost.setConfig(requestConfig);try {if (null != strParam) {// 解決中文亂碼問題StringEntity entity = new StringEntity(strParam, "utf-8");entity.setContentEncoding("UTF-8");entity.setContentType("application/x-www-form-urlencoded");httpPost.setEntity(entity);}CloseableHttpResponse result = httpClient.execute(httpPost);// 請求發送成功,并得到響應if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {String str = "";try {// 讀取服務器返回過來的json字符串數據str = EntityUtils.toString(result.getEntity(), "utf-8");// 把json字符串轉換成json對象jsonResult = JSONObject.parseObject(str);} catch (Exception e) {logger.error("post請求提交失敗:" + url, e);}}} catch (IOException e) {logger.error("post請求提交失敗:" + url, e);} finally {httpPost.releaseConnection();}return jsonResult;}/*** 發送get請求* * @param url* 路徑* @return*/public static JSONObject httpGet(String url) {HttpHost proxy = new HttpHost("localhost", 8888);RequestConfig config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(10000).setSocketTimeout(15000).build();CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();// get請求返回結果JSONObject jsonResult = null;// 發送get請求HttpGet request = new HttpGet(url);request.setConfig(requestConfig);try {CloseableHttpResponse response = client.execute(request);// 請求發送成功,并得到響應if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 讀取服務器返回過來的json字符串數據HttpEntity entity = response.getEntity();String strResult = EntityUtils.toString(entity, "utf-8");// 把json字符串轉換成json對象jsonResult = JSONObject.parseObject(strResult);} else {logger.error("get請求提交失敗:" + url);}} catch (IOException e) {logger.error("get請求提交失敗:" + url, e);} finally {request.releaseConnection();}return jsonResult;}}
package learn_b;import java.net.URLDecoder;
import java.net.URLEncoder;import com.alibaba.fastjson.JSONObject;
import com.learn.utils.HttpClientUtils;public class Test001 {public static void main(String[] args) {// Java 提供Http協議 特殊字符轉碼類String encode = URLEncoder.encode("1+1");System.out.println("encode:" + encode);System.out.println("decode:" + URLDecoder.decode(encode));String userNameUrl = "http://127.0.0.1:8080/indexPage?userName=" + URLEncoder.encode("1+1");JSONObject result = HttpClientUtils.httpGet(userNameUrl);System.out.println("result:" + result);// 注意事項 不要整個URL進行編碼,只是針對于參數編碼}}
package com.learn.api.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import com.learn.base.BaseApiService;
import com.learn.base.ResponseBase;// http協議特殊字符處理
@RestController
public class IndexController extends BaseApiService {// 1. 什么是特殊字符處理(rpc遠程通訊 實現加密 + ?) 正好和http特殊相同,導致會轉成空格// 2. 注意事項@RequestMapping("/indexPage")public ResponseBase indexPage(String userName) {System.out.println("userName:" + userName);return setResultSuccessData(userName);}}
?
總結
以上是生活随笔為你收集整理的URL特殊字符转码的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。