Skip to content

Instantly share code, notes, and snippets.

@chemp7
Last active April 20, 2021 03:57
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save chemp7/548fccd3d2509811843e42f1198c040c to your computer and use it in GitHub Desktop.
Save chemp7/548fccd3d2509811843e42f1198c040c to your computer and use it in GitHub Desktop.
package chemp.notes.linenotify;
import java.io.*;
import java.net.*;
import java.util.regex.Pattern;
public class LineNotify {
private static final String strEndpoint = "https://notify-api.line.me/api/notify";
public boolean callEvent(String token, String message) {
boolean result = false;
try {
message = replaceProcess(message);
message = URLEncoder.encode(message, "UTF-8");
String strUrl = strEndpoint;
URL url = new URL( strUrl );
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.addRequestProperty("Authorization", "Bearer " + token);
connection.setRequestMethod( "POST" );
connection.addRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );
connection.setDoOutput( true );
String parameterString = new String("message=" + message);
PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
printWriter.print(parameterString);
printWriter.close();
connection.connect();
int statusCode = connection.getResponseCode();
if ( statusCode == 200 ) {
result = true;
} else {
throw new Exception( "Error:(StatusCode)" + statusCode + ", " + connection.getResponseMessage() );
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private String replaceProcess(String txt){
txt = replaceAllRegex(txt, "\\\\", "¥"); // \
return txt;
}
private String replaceAllRegex(String value, String regex, String replacement) {
if ( value == null || value.length() == 0 || regex == null || regex.length() == 0 || replacement == null )
return "";
return Pattern.compile(regex).matcher(value).replaceAll(replacement);
}
}
@SuBoLun
Copy link

SuBoLun commented Aug 1, 2019

hi, i just try the code but the error message shows :
stop at : throw new Exception( "Error:(StatusCode)" + statusCode + ", " + connection.getResponseMessage() );
error : java.lang.Exception: Error:(StatusCode)400, null
at com.egroup.util.LineUtil.callEvent(LineUtil.java:37)
at com.egroup.util.LineUtil.main(LineUtil.java:12)

i just write a main in same class and use the function like
LineNotify lineNotify = new LineNotify ();
lineNotify .callEvent("myToken","myMessage");
what may cause this error~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment