这是我的代码:
public class JavaSoapUi {
public static void main(String[] args) throws Exception {
String requestUrl = "myurl";
URLConnection connection =new URL(requestUrl).openConnection();
System.out.println( "orignal url: " + connection.getURL() );
connection.connect();
System.out.println( "connected url: " + connection.getURL() );
HttpPost httpPost = new HttpPost(requestUrl);
String username = "user";
String password = "pass";
String encoded = DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"));
httpPost.addHeader("AUTHORIZATION", "Basic " + encoded);
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse response = httpClient.execute(httpPost);
System.out.println("Response" + response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println("ResponseString" + responseString);
EntityUtils.consume(entity);
}
我收到输出错误:HTTP / 1.1 301永久移动
如果我在SOAP UI中使用了用户名和密码通过使用基本身份验证,我可以获得输出。但是当我在Java代码中使用相同的用户名和密码时,我收到错误。
任何人帮助我。
答案 0 :(得分:0)
由于您添加了RFC中定义的标头,因此Authoritzation
http-header看起来不错。此外,如果问题出在您的Authoritzation
上,那么您的通话必须收到Error HTTP 401 Unauthorized
,而不是您正在接收Error HTTP 301 - Moved permanently
,因此错误可能与您的url
有关。检查location
错误回复的http-header
301
,看看您的服务是否正确url
。
基于OP评论的编辑
正如我所说,您检查了来自location
错误回复的301
标题,如果您更改了url
,https://
似乎是url
,现在您正在接收Error: unable to find valid certification path to requested target
这是因为您的客户必须信任服务器证书,为此,从您的url
下载服务器证书并将其加载到JRE的信任存储区中使用follow命令执行客户端的地方(正确的方法是添加服务器证书的certificate authority
,但是直接执行测试加载服务器证书就足够了)。
keytool -import -alias somealias -file serverCertificate.cer -keystore JRE_HOME/lib/security/cacerts
请注意,keytool
位于JAVA_HOME/bin/keytool
中的java发布内,JRE_HOME/lib/security/cacerts
信任存储的默认密码为changeit
。
希望这有帮助,