I have to translate a curl command: curl -X GET --header 'Accept: application/json' 'https://terminologies.gfbio.org/api/terminologies/' to java. I want to send this http request to the specified address. The response is then to be stored into a string in java, can you please tell me the translation?
You can archieve it without an additional library with plain JAVA. For JAVA versions v11+ I would prefer the approach @MarcoLucidi suggested.
String content="";
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
URL url = new URL("https://terminologies.gfbio.org/api/terminologies/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("accept", "application/json");
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
content+=inputLine;
in.close();
System.out.println(content);
if you are using at least java 11, you can use the new built in http client . for example:
import java.io.IOException;
import java.net.URI;
import java.net.http.*;
import java.net.http.HttpResponse.BodyHandlers;
public class HttpExample
{
public static void main(String[] args)
{
HttpClient client = HttpClient.newHttpClient();
HttpRequest req = HttpRequest
.newBuilder()
.uri(URI.create("https://terminologies.gfbio.org/api/terminologies/"))
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> resp = client.send(req, BodyHandlers.ofString());
String body = resp.body();
System.out.println(body);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
$ javac HttpExample.java
$ java HttpExample
{
"request":{
"query":"http://terminologies.gfbio.org/api/terminologies/",
"executionTime":"Sun Jun 28 05:00:03 CEST 2020"
},
"results":[
{
"name":"Biological Collections Ontology",
"acronym":"BCO",
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.