Skip to content

Instantly share code, notes, and snippets.

@yoga1290
Last active December 10, 2015 13:09
Show Gist options
  • Save yoga1290/4439107 to your computer and use it in GitHub Desktop.
Save yoga1290/4439107 to your computer and use it in GitHub Desktop.
URLConnection thread class, where I used to handle URLConnections on Android!
import java.io.*;
import java.net.*;
/**
* Just make your activity "implements URLThread_CallBack"
* ... where URLCallBack(String response) is called after the URLConnection returns a something
* Just new URLThread("http://google.com", this, "").start() will start a new thread ;)
*/
interface URLThread_CallBack
{
public void URLCallBack(String response);
}
public class URLThread extends Thread
{
private String url,POSTdata="";
private URLThread_CallBack callback;
public URLThread(String url,URLThread_CallBack callback,String POSTdata)
{
this.url=url;
this.callback=callback;
this.POSTdata=POSTdata;
}
@Override
public void run()
{
String res="";
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(this.url);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(POSTdata.getBytes().length));
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (POSTdata);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
byte buff[]=new byte[500];
int i;
while((i=is.read(buff))>-1)
res+=new String(buff,0,i);
is.close();
if(callback!=null) //still alive?
callback.URLCallBack(">"+res);
} catch (Exception e) {
e.printStackTrace();
callback.URLCallBack("Error:"+e.getMessage());
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment