gpt4 book ai didi

java - 如何通过 ssl 发送请求?

转载 作者:搜寻专家 更新时间:2023-10-31 20:34:39 24 4
gpt4 key购买 nike

我正在尝试从本地主机向服务器发送请求,但它返回以下错误。

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();
}
}

最佳答案

当您应该使用 HttpsURLConnection 时,您正在尝试将 HttpURLConnection 用于 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com