How to send discord webhook message in Java? - java

I'm trying to send a discord webhook message from Java.
I found a way in this website.
But when i tried, it didn't work.
package com.company;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class Discord {
public static void main(String[] args) throws Exception {
URL url = new URL("https://discord.com/api/webhooks/my_webhook_url");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
String jsonInputString = "{" +
"username : \"Bot\", " +
"content : \"Hello World\"" +
"}";
try(OutputStream os = con.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
}
}
I'm just using this for a one way message so, i guess this should work.
But why doesn't it?

add
con.addRequestProperty("User-Agent", "Mozilla");

Related

Sending Discord Webhook with java

I want something like this, but with a file attachment, so i can send an embed and under it the image. It doesnt have to like this exactly, but it should like something like this: enter image description here
package com.StrgC;
import java.io.OutputStream;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class WarningSending {
public static void SendWarning() {
///////////////////////////////////////////////
// CONFIG
String tokenWebhook = "";
String title = "";
String message = "";
///////////////////////////////////////////////
String jsonBrut = "";
jsonBrut += "{\"embeds\": [{"
+ "\"title\": \""+ title +"\","
+ "\"description\": \""+ message +"\","
+ "\"color\": 15925248"
+ "}]}";
try {
URL url = new URL(tokenWebhook);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.addRequestProperty("Content-Type", "application/json");
con.addRequestProperty("User-Agent", "Java-DiscordWebhook-BY-Gelox_");
con.setDoOutput(true);
con.setRequestMethod("POST");
OutputStream stream = con.getOutputStream();
stream.write(jsonBrut.getBytes());
stream.flush();
stream.close();
con.getInputStream().close();
con.disconnect();
} catch (Exception e) {
e.printStackTrace()
}
}
}

Calling GET API in java using bearer token

I need to send bearer token for the below code. Below code is working but I have to call another rest end point with GET which is protected by token. What addition I need to do in below code? I just want to replace url and need to add bearer token.
package com.shruti.getapi;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
public class NetClientGet {
public static void main(String[] args) {
try
{
System.out.println("Inside the main function");
URL weburl=new URL("http://dummy.restapiexample.com/api/v1/employees");
HttpURLConnection conn
= (HttpURLConnection) weburl.openConnection(Proxy.NO_PROXY);
//HttpURLConnection conn = (HttpURLConnection) weburl.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
System.out.println("Output is: "+conn.getResponseCode());
System.out.println("Output is: ");
System.setProperty("http.proxyHost", null);
//conn.setConnectTimeout(60000);
if(conn.getResponseCode()!=200)
{
System.out.println(conn.getResponseCode());
throw new RuntimeException("Failed : HTTP Error Code: "+conn.getResponseCode());
}
System.out.println("After the 2 call ");
InputStreamReader in=new InputStreamReader(conn.getInputStream());
BufferedReader br =new BufferedReader(in);
String output;
while((output=br.readLine())!=null)
{
System.out.println(output);
}
conn.disconnect();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
conn.setRequestProperty("Accept", "application/json");
You want this idea, but for the Authorization header.
Authorization = credentials
RFC 6750 includes an ABNF description of the credentials for an OAuth2 Bearer Token
b64token = 1*( ALPHA / DIGIT /
"-" / "." / "_" / "~" / "+" / "/" ) *"="
credentials = "Bearer" 1*SP b64token

Response code is 400 while using HttpURLConnection to POST in java for REST API

I am a newbie to REST API's. I need to post to the website, but I get response code as 400 and content-type as text/plain
If I use Advanced REST Client Application of google, I get different results. The response code is 500 and the content-type is text/html.
Am I not ending the post data (query1) correctly? Is this the correct way of doing it? Do I need to use JAX-RS? Can someone please help? Appreciate it.
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import org.testng.annotations.Test;
public class RestfullAPIHttpURLConnection {
#Test
public static void postS() throws Exception {
URL url;
HttpURLConnection connection = null;
String urlParameters = "email=tester0#xxx.com&profileName=Tester0&password=test&roleId=1";
String email = "tester0#xxx.com";
String profileName = "Tester0";
String password = "test";
int roleId = 1;
String query = String.format("email=%s&profileName=%s&password=%s&roleId=%s",
(email),
URLEncoder.encode(profileName),
URLEncoder.encode(password),
(roleId));
String query1="?";
query1 = query1.concat(query);
System.out.println("query1: " +query1);
String type = "application/json";
url = new URL("http://......com");
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty( "Content-Type", type );
connection.setRequestProperty( "charset", "utf-8");
connection.setUseCaches( false );
// creates an output stream on the connection and opens an OutputStreamWriter on it:
OutputStream output = connection.getOutputStream();
Writer writer = new OutputStreamWriter(output, "UTF-8");
// client's output is the server's input.
writer.write(URLEncoder.encode(query1, "UTF-8"));
String contentType=connection.getContentType();
int responseCode=connection.getResponseCode();
int len = connection.getContentLength();
String rmsg = connection.getResponseMessage();
System.out.println("ContentType: " +contentType);
System.out.println("ResponseCode: " +responseCode);
System.out.println("Content length: " +len);
System.out.println("URL " + connection.getURL());
System.out.println("Response msg: " + rmsg);
}
}
Use Jersey Client:
Here an example:
final WebTarget target = ClientBuilder.newClient().target("http://......com");
final WebTarget webTargetWithParams = target.queryParam("email", "tester0#xxx.com")
.queryParam("profileName", "Tester0")
.queryParam("password", "test")
.queryParam("roleId", "1");
final Response response = webTargetWithParams.request().get();
System.out.println(response.readEntity(String.class));

Trying to HTTP POST But Getting MalformedURLException: no protocol: yahoo.com

Overall I'm trying to write a script that captures the servers' response to an HTTP POST using java.
Unfortunately, I'm stuck at encoding the URL portion of it. While I followed several online example on encoding a URL, I still get MalformedURLException...
Any idea what might go wrong in the encoding process?
The error:
$ java client_post
Sending Http POST request
Exception in thread "Main Thread" java.net.MalformedURLException: no
protocol: http%3A%2F%2Fyahoo.com
at java.net.URL.<init>(URL.java:567)
at java.net.URL.<init>(URL.java:465)
at java.net.URL.<init>(URL.java:414)
at client_post.sendPost(client_post.java:30)
at client_post.main(client_post.java:23)
The code:
//package client_post;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class client_post {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
client_post http = new client_post();
System.out.println("\nSending Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
//String url =<host:port/create/service>
String url = "http://yahoo.com";
String EncoderUrl = URLEncoder.encode(url, "UTF-8");
URL obj = new URL(EncoderUrl);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language","en-US,en;q=0.5");
String urlParameters = "<string base64>";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
System.out.println(response.toString());
}
}
When you are encoding url your url becomes like below
http%3A%2F%2Fyahoo.com
Dont encode untill you have something special in it.
Your programm is also throwing class cast exception
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
Above should be like below
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
Below is working programm.
package com.ds.portlet.library;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class client_post {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
client_post http = new client_post();
System.out.println("\nSending Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
//String url =<host:port/create/service>
String url = "http://yahoo.com";
// String EncoderUrl = URLEncoder.encode(url, "UTF-8");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language","en-US,en;q=0.5");
String urlParameters = "<string base64>";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
System.out.println(response.toString());
}
}
It looks like you're trying to encode the entire URL, including the :// and similar characters. The purpose of URL encoding is to hide those characters in a path or query part, and they shouldn't be encoded in the main URL. Use URLEncoder only for parameters or application/x-www-form-urlencoded contents.

Urban Airship Push code

I've followed the UA tutorials and got my APID , and successfully recieved test push message on my android device.
Now the next thing that I like to do is to target my device using JAVA and send push messaged.
From what I've seen so far the best way to achieve this is using their web API.
However When I'm trying to send a post message I always get the following error :
java.io.IOException: Server returned HTTP response code: 401 for URL: https://go.urbanairship.com/api/push/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at com.Sender.Sender.main(Sender.java:56)
This is the code that I use :
package com.Sender;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class Sender {
/**
* #param args
*/
public static void main(String[] args) {
try {
String responseString = "";
String outputString = "";
String username = "MWMoRVhmRXOG6IrvhMm-BA";
String password = "ebsJS2iXR5aMJcOKe4rCcA";
MyAuthenticator ma= new MyAuthenticator(username, password);
Authenticator.setDefault(ma);
URL url = new URL("https://go.urbanairship.com/api/push/");
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConnection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
String APID = "23eef280-19c8-40fc-b798-788f50e255a2";
String postdata = "{\"android\": {\"alert\": \"Hello from JAVA!\"}, \"apids\": [\""+APID+"\"]}";
byte[] buffer = new byte[postdata.length()];
buffer = postdata.getBytes("UTF8");
bout.write(buffer);
byte[] b = bout.toByteArray();
httpConn.setRequestProperty("Content-Length",
String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "application/json");
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
out.write(b);
out.close();
InputStreamReader isr = new InputStreamReader(
httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
System.out.println(outputString);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Can you help me please ?
HTTP 401 represent Unauthorized access. In your code even though your created Authenticator, you didn't provide it as part of post request header. Here is tutorial on how to set authenticator for a URLConnection.

Categories

Resources