创建Http.java
public class Http {
private getReturnClick click;
private Handler mHandler = new Handler(Looper.myLooper()) {
@Override
public void handleMessage(Message remsg) {
super.handleMessage(remsg);
if (remsg.what == 1) {
click.success((String) remsg.obj);
} else {
click.fail();
}
}
};
public void get(String url1) {
Message msg = Message.obtain();
new Thread() {
public void run() {
try {
URL url = new URL(url1);
HttpURLConnection Connection = (HttpURLConnection) url.openConnection();
Connection.setRequestMethod("GET");
Connection.setConnectTimeout(10000);
Connection.setReadTimeout(10000);
int responseCode = Connection.getResponseCode();
if (responseCode == Connection.HTTP_OK) {
InputStream inputStream = Connection.getInputStream();
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int length = 0;
while ((length = inputStream.read(bytes)) != -1) {
arrayOutputStream.write(bytes, 0, length);
arrayOutputStream.flush();
}
msg.what = 1;
msg.obj = arrayOutputStream.toString();
mHandler.sendMessage(msg);
} else {
msg.what = -1;
mHandler.sendMessage(msg);
}
} catch (Exception e) {
msg.what = -1;
mHandler.sendMessage(msg);
}
}
}.start();
}
public void post(String url1, String data) {
Message msg = Message.obtain();
new Thread() {
public void run() {
try {
URL url = new URL(url1);
HttpURLConnection Connection = (HttpURLConnection) url.openConnection();
Connection.setRequestMethod("POST");
Connection.setConnectTimeout(3000);
Connection.setReadTimeout(3000);
Connection.setDoInput(true);
Connection.setDoOutput(true);
Connection.setUseCaches(false);
Connection.connect();
DataOutputStream dos = new DataOutputStream(Connection.getOutputStream());
String title = data;
dos.write(title.getBytes());
dos.flush();
dos.close();
int responseCode = Connection.getResponseCode();
if (responseCode == Connection.HTTP_OK) {
InputStream inputStream = Connection.getInputStream();
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int length = 0;
while ((length = inputStream.read(bytes)) != -1) {
arrayOutputStream.write(bytes, 0, length);
arrayOutputStream.flush();
}
msg.what = 1;
msg.obj = arrayOutputStream.toString();
mHandler.sendMessage(msg);
} else {
msg.what = 0;
mHandler.sendMessage(msg);
}
} catch (Exception e) {
msg.what = 0;
mHandler.sendMessage(msg);
}
}
}.start();
}
public interface getReturnClick {
void success(String re);
void fail();
}
public void setGetReturnClick(getReturnClick click) {
this.click = click;
}
}
使用时创建对象直接使用
Http http = Http();
http.get("网址");
http.post("网址","传递参数");
http.setGetReturnClick(new Http.getReturnClick(){
@Override
public void success(String text){
}
@Override
public void fail(){
}
});