我正在尝试从localhost向服务器发送请求,但它返回以下错误。
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
代码
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class Test {
public void connectMyServer(){
Login auth = new Login("username", "password");
JAXBContext cntx = JAXBContext.newInstance(Login.class);
Marshaller m = cntx.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
try {
URL url = new URL("https://www.server.com/requests");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setDoOutput(true);
con.setDoInput(true);
OutputStream os = con.getOutputStream();
m.marshal(auth, os);
m.marshal(auth, System.out);
os.flush();
con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
con.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:1)
当您使用HttpURLConnection
时,您正尝试将HttpsURLConnection
用于SSL。
编辑:
我试过了:
import java.net.URL;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class Test
{
public static void main(String[] args) throws Exception
{
URL url = new URL("https://www.google.com");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
Map<String,List<String>> fields = con.getHeaderFields();
con.disconnect();
}
}
它运行没有问题。
您的错误消息表明远程服务器正在响应,就好像它说的是HTTP,而不是HTTPS,无论您的技术团队说什么。