我使用下面的代碼將基本http身份驗證的憑據設置爲使用Spring Security的服務器。 不幸的是我有像é,ò等特殊字符的問題...我在服務器上收到問號而不是正確的字符 有人知道如何解決它?我一直在尋找設置編碼沒有成功使用Spring身份驗證的特殊字符
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));
}
}
然後我調用Web服務與彈簧類:
RestClient restClient = new RestClient(username, password);
response = restClient.getForObject(addQueryParam(url, queryParams), Response.class);
UPDATE:
使用此代碼我有同樣的錯誤(問號而不是特殊字符)。一些想法?
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;
}
}
「不幸的是我有特殊字符,如E,O等問題。」好的,問題到底是什麼? – rmlan
我收到服務器問號而不是正確字符 – luca