Last active
April 20, 2021 03:57
-
-
Save chemp7/548fccd3d2509811843e42f1198c040c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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~