簡體   English   中英

具有Spring身份驗證的特殊字符

[英]Special character with Spring authentication

我使用以下代碼,在其中為使用Spring Security的服務器設置基本http身份驗證的憑據。 不幸的是,我遇到諸如é,ò等特殊字符的問題。我在服務器上收到問號而不是正確的字符有人知道如何解決它嗎? 我一直發現設置編碼沒有成功

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

public class RestClient extends RestTemplate { 
   public RestClient(String username, String password) {
         CredentialsProvider credsProvider = new BasicCredentialsProvider();
         credsProvider.setCredentials(
                 new AuthScope(null, -1),
                 new UsernamePasswordCredentials(username, password));
         HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
         setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
        }
    }

然后我用spring類調用Web服務:

RestClient restClient = new RestClient(username, password);
response = restClient.getForObject(addQueryParam(url, queryParams), Response.class);

更新:

使用此代碼,我有相同的錯誤(問號而不是特殊字符)。 有想法嗎

public class RestClient extends RestTemplate {
    private static RestClient instance;

    private RestClient(String username, String password) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope(null, -1),
                new UsernamePasswordCredentials(username, password));
        HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
        setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
    }

    public static synchronized RestClient getInstance(String username, String password){
        if (instance == null){
            instance = new RestClient(username, password);
            instance.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        }
        return instance;

    }  
}

轉到您的web.xml並將URIEncoding設置為UTF-8

<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443" 
       URIEncoding="UTF-8"/>


<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8" />

資源

您應該添加正確的消息轉換器在我遇到類似問題的情況下,我使用此配置:

RestTemplate rt = new RestTemplate();
rt.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));

經過這一切都很好

安傑洛

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM