/*
* I guess this example will help you -- Don't copy paste this , try to understand this
* I've edited this here so it may have error, so as I said, try to understand --don't copy paste--
* @author oseamiya
*/
@SimpleFunction
public void Post(String urls){
(new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try {
URL url = new URL(urls);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod(method);
int responseCode = httpURLConnection.getResponseCode();
if (responseCode / 100 == 2) {
inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
String res = convertStreamToString(inputStream);
if(res != null){
activity.runOnUiThread(new Runnable(){
@Override
public void run(){
OnSuccess(res);
}
});
}
} else {
String res = convertStreamToString(httpURLConnection.getErrorStream());
if(res != null){
activity.runOnUiThread(new Runnable(){
@Override
public void run(){
OnError(res);
}
});
}
}
} catch(Exception e){
e.printStackTrace();
// You can trigger OnError method here in UI thread too
} finally {
if (httpUrlConnection != null) {
httpUrlConnection.disconnect();
}
})).start();
}
@SimpleEvent
public void OnSuccess(String data){
EventDispatcher.dispatchEvent(this, "OnSuccess", data);
}
@SimpleEvent
public void OnError(String error){
EventDispatcher.dispatchEvent(this, "OnError", error);
}
private String convertStreamToString(InputStream is) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
try {
int len;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
return baos.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
1 Like