Sending an HTTPS request from a Java application
What are the ways to send https requests from a desktop java application? The source code example is particularly interesting.
6
Author: Nicolas Chabanovsky, 2011-02-15
3 answers
The most primitive way is to use URLConnection
. Here is an example without error handling, encodings, and other husks:
public static void main(String[] args) throws Exception {
URLConnection connection = new URL("https://www.dev.java.net/servlets/ProjectList").openConnection();
InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
char[] buffer = new char[256];
int rc;
StringBuilder sb = new StringBuilder();
while ((rc = reader.read(buffer)) != -1)
sb.append(buffer, 0, rc);
reader.close();
System.out.println(sb);
}
If it turns out that the standard URLConnection
(more precisely, it is actually created HttpsUrlConnection
) if something doesn't work, then use the Apache HTTP Client.
12
Author: cy6erGn0m, 2017-11-18 22:17:07
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null)
sb.append(inputLine);
in.close();
System.out.println(sb);
}
}
Source https://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html
1
Author: FORTRAN, 2016-10-12 17:10:15
You can use the http-request built on the apache http api.
String uri = "https://www.dev.java.net/servlets/ProjectList";
HttpRequest<String> httpRequest = HttpRequestBuilder.createGet(uri, String.class)
.responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build();
public void send(){
ResponseHandler<String> response = httpRequest.execute(someParamsYouWant);
System.out.println(response.getStatusCode());
System.out.println(response.get()); //retuns response body
}
1
Author: Beno Arakelyan, 2017-09-17 12:33:29