I have a line of code that I'm using in a shell script to send notifications to some users. I need to be able to use it in a Java application as well, but I am stuck on how to convert it to something Java would understand.
This is what the shell command looks like:
curl -u key:secret -d email=user#example.com \
--data-urlencode msg="test message" \
--data-urlencode url="http://www.airgramapp.com/welcome" \
https://api.airgramapp.com/1/send -k
Here's what I have so far:
URL url = new URL("curl -u key:secret -d email=user#example.com \
--data-urlencode msg="test message" \
--data-urlencode url="http://www.airgramapp.com/welcome" \
https://api.airgramapp.com/1/send -k");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
}
Any help or guidance in the right direction would be greatly appreciated!
Related
I need to transform this curl to java code
curl -G \
-u "{user}":"{pass}" \
-d "version=2018-03-16" \
-d "the msg" \
-d "features=entities" \
-d "entities.model={modelID}" \
"https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze"
and my java code is something like that
URL url = new URL(uri.toString());
HttpURLConnection handle = (HttpURLConnection) url.openConnection();
String userpass = "{user}:{pass}";
new Base64();
String basicAuth = "Basic " + new String(Base64.encode(userpass.getBytes()));
handle.setRequestMethod("POST");
handle.setRequestProperty("Content-Type", "application/json");
handle.setRequestProperty("Authorization", basicAuth);
handle.setRequestProperty("version", "2018-03-16");
handle.setRequestProperty("text", params.getParameterString());
handle.setRequestProperty("features", "entities");
handle.setRequestProperty("entities.model", wksModel);
handle.setDoOutput(true);
This gives me error 400 so you do not know where my mistake, I hope you can help me
I'm trying to implement an API with a GraphQL query in my android app but having trouble with how to go about converting the cURL to java. I'm relatively new to programming so I've been trying to follow tutorials and questions on here but having no luck for the past few days.
Basically the cURL command sends a GraphQL query and returns a json which I'd like to extract specific data from.
The cURL command is as follows
curl -v 'https://api.url/' \
-H 'content-type: application/json' \
-H 'accept: application/json' \
-H 'x-api-key: <YOUR_API_KEY>' \
--data-binary '{"query":"{ Search(query: \"searchVariable\") {items{description} } }","variables":"{}","operationName":null}'
When I run this in the terminal it returns a json string. I would like to return this in my app and extract data from the json. I think I can do this using a json object but cannot get the data in the first place
Here is one method I tried using another tutorial, it builds successfully but crashes as soon as I attempt to call the method.
public static String URLConnection() throws IOException, JSONException {
URL url = new URL("https://api./api/graphql/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.addRequestProperty("curl", "'https:/api/graphql/'");
connection.addRequestProperty("content-type", "application/json");
connection.addRequestProperty("accept", "application/json");
connection.addRequestProperty("x-api-key", "'xxxxxxxxxxx'");
connection.addRequestProperty("--data-binary", "{\"query\":\"{Search(query:\"Query\"){items{description}}}\",\"variables\":\"{}\",\"operationName\":null}");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
JSONObject jsonParam = new JSONObject();
jsonParam.getString("description");
OutputStream os = connection.getOutputStream();
os.write(Integer.parseInt(URLEncoder.encode(jsonParam.toString(), "UTF-8")));
os.close();
try {
InputStream in = connection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
connection.disconnect();
}
}
i have this command:
wget -O prova.csv --header="prova-user: guest" --header="prova-passwd: guest"
"http://www.....................80&albedo=0.2&horizon=1"
i want to do a batch scheduled in Java but I can not connect. When I try to take the imputstream return me this error:
ERROR message -8: Unregistered IP address
This is my piece of code:
URL myURL = new URL(url);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
String userCredentials = "guest:guest";
String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
myURLConnection.setRequestProperty ("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
// Show page.
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream(), "UTF-8"));
for (String line; ((line = reader.readLine()) != null);) {
System.out.println(line);
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException ignore) {}
}
is it possible? and how can I do it?
Thanks in advance
You had provided 2 completely different commands.
The first is a wget that send in HTTP headers a sort of authentication infos, and GET a result.
The second is a java program that perform an HTTP request in POST with basic authentication.
If the first command is working, than you should forget about the basic authentication and set the proper HTTP headers as you did in the wget command.
I don't know why you try a POST, if the wget looks as a normal GET request.
Just use a GET request in java too.
And it should work.
About the error, I suppose is the server that sent you such error message.
So it could be as you haven't correctly authenticated.
But it is a strange error, I'm expecting such kind of error if the server have a white list of IP addresses allowed to connect.
Are you running the wget and the java code on the same server?
I am using JSch to ssh to multiple servers and run few commands. My output file capture everything. But I am looking for a way to capture only the server respond.
Code:
try (OutputStream log = new BufferedOutputStream( new FileOutputStream("OUTPUT_FILE"))) {
JSch jsch = new JSch();
for (String host : jssh.listOfhost()) {
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(getProperties());
session.connect(10 * 1000);
Channel channel = session.openChannel("shell");
channel.setOutputStream(log, true);
try (PipedInputStream commandSource = new PipedInputStream();
OutputStream commandSink = new PipedOutputStream(commandSource)) {
CommandSender sender = new CommandSender(commandSink);
Thread sendThread = new Thread(sender);
sendThread.start();
channel.setInputStream(commandSource);
channel.connect(15 * 1000);
sendThread.join();
if (sender.exception != null) {
throw sender.exception;
}
}
channel.disconnect();
session.disconnect();
}
}
Current Output:
Last login: Thu Jan 14 15:06:17 2016 from 192.168.1.4
mypc:~ user$
mypc:~ user$ hostname
mypc
mypc:~ user$ df -l | grep disk0s3 |tr -s [:blank:]|cut -d ' ' -f 7
19098537
but I only want to output the following
mypc 19098537
Which is an outcome of the following two commands
hostname
df -l | grep disk0s3 |tr -s [:blank:]|cut -d ' ' -f 7
Use exec channel, not shell channel. The exec channel is intended for command execution. The shell channel is intended for implementing an interactive session. That's why you get all the prompts and such. You do not get these in the exec channel.
See the official JSCh example for using exec channel.
If you need to read both stdout and stderr, see my answer to How to read JSch command output?
I am trying to run the following command using Ganymed-SSH2 (ch.ethz.ssh2):
nohup sudo mycommand &
It works when I run directly from command line, but nothing happens when I run it using the Java code below.
Connection connection = new Connection(server);
connection.connect();
if (!connection.authenticateWithPassword(userName, password)) {
throw new IOException("Failed to authenticate with user " + userName + "on host: " + connection.getHostname());
}
Session session = connection.openSession();
session.requestDumbPTY();
session.execCommand("nohup sudo mycommand &");
session.close();
connection.close();
The command works via the execCommand() method if I exclude the & (but this won't give me my required results), but nothing happens with & there.
Any ideas what is going wrong?
(Note: sudo does not require a password)
I've found a good hint to solve this issue reading the nohup wikipedia page. Combine nohup and ssh require stdin / std[out|err] to be redirected.
If your server doesn't have Defaults requiretty in /etc/sudoers you can simply use:
sess.execCommand("nohup sudo <yourCommand> 2>&1 >nohup.out </dev/null &");
Entire code:
import ch.ethz.ssh2.*
String hostname = "localhost";
String username = "gsus";
File keyfile = new File("/home/gsus/.ssh/id_rsa");
String keyfilePass = "";
try {
Connection conn = new Connection(hostname);
conn.connect();
boolean isAuthenticated=conn.authenticateWithPublicKey(username,keyfile,keyfilePass);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
Session sess=conn.openSession();
//Don't use this
//sess.requestDumbPTY();
sess.execCommand("nohup sudo ping -c 100 www.yahoo.com 2>&1 >nohup.out </dev/null &");
sess.close();
conn.close();
}
catch ( IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
If instead your server /etc/sudoers file contains Defaults requiretty (#user5222688) you have to switch using session.startShell()
import ch.ethz.ssh2.*
String hostname = "localhost";
String username = "gsus";
File keyfile = new File("/home/gsus/.ssh/id_rsa");
String keyfilePass = "";
try {
Connection conn = new Connection(hostname);
conn.connect();
boolean isAuthenticated=conn.authenticateWithPublicKey(username,keyfile,keyfilePass);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
Session sess=conn.openSession();
sess.requestPTY("xterm");
sess.startShell();
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader input = new BufferedReader(new InputStreamReader(stdout));
OutputStream out = sess.getStdin();
out.write("nohup sudo <yourCommand> 2>&1 >nohup.out </dev/null &\n".getBytes());
out.flush();
while (!input.readLine().contains("stderr")) {
//Simply move on the stdout of the shell till our command is returned
}
sess.close();
conn.close();
}
catch (IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}