Please post your Web Driver questions in official Web Driver forum

Sunday, September 4, 2016

Use curl in java without third party libraries

curl is a command line tool which is used to transfer data to and from server. For example, following command can be used to get oAuth token using curl command -


curl -u user:’password https://token.auth.xxx.com/


o/p - xxxxaaf9-zzzz-4be7-xyz6-xxxxxxxxxx


Here is the example of executing curl from java without using any third party library -



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class CurlTest {
public static void main(final String[] args) throws IOException {
URL url = new URL("https://token.xxx.com/");
URLConnection uc = url.openConnection();
String userPass = "tarun" + ":" + "xxx";
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes());
uc.setRequestProperty("Authorization", basicAuth);
InputStream in = uc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")))
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
}
}
Fork me on GitHub