我正在尝试从本地主机向服务器发送请求,但它返回以下错误。
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();
}
}
最佳答案
您应该在使用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一样在响应。
关于java - 如何通过SSL发送请求?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20160701/