我使用下面的代码,我将基本http身份验证的凭据设置为使用Spring Security的服务器。 不幸的是我对é,ò等特殊字符有问题...我在服务器上收到问号而不是正确的字符 有人知道怎么解决吗?我一直在寻找设置编码而没有成功
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 class调用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;
}
}
答案 0 :(得分:0)
转到您的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" />
答案 1 :(得分:0)
您应该添加正确的邮件转换器 在我遇到类似问题的情况下,我使用了这个配置:
RestTemplate rt = new RestTemplate();
rt.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
此后一切都很好
安吉洛