开发者

Connecting to a https url from java

开发者 https://www.devze.com 2023-02-06 12:50 出处:网络
How do I connect to an URL using Java? I am looking to get the content from an https webs开发者_StackOverflow社区ite.I hope this helps.

How do I connect to an URL using Java? I am looking to get the content from an https webs开发者_StackOverflow社区ite.


I hope this helps. Dont forget to URLEncode your URL. To see what the header for your specific request should look like, you could for example use Firebug extension for Firefox.

String url=YOUR_URL;
String message=YOUR_REQUEST_HEADER

SocketFactory sslSocketFactory = SSLSocketFactory.getDefault();
String response = "";
try {
 URL url = new URL(url);
 Socket socket = sslSocketFactory.createSocket(url.getHost(),     url.getPort()==-1?443:url.getPort());

PrintWriter toServer = new PrintWriter(socket.getOutputStream());
toServer.println(message);
toServer.flush();

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));

char[] buf = new char[4096];
int bytesRead;
while((bytesRead = in.read(buf)) != -1){
 response = response + new String(buf).substring(0, bytesRead);
}

in.close();
socket.close();

} catch (MalformedURLException e) {
 e.printStackTrace();
} catch (IOException e){
 e.printStackTrace();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消