public class HelperAsnc {
public HelperAsnc(){}
//get请求
public HelperAsnc get(String url){
doHttp(url,"GET","");
return this;
}
//联网请求
private void doHttp(String url,String method,String string){
myAsyncTask=new MyAsyncTask(url,method,string);
myAsyncTask.execute();
}
//post请求
public HelperAsnc post(String url,String string){
doHttp(url,"POST",string);
return this;
}
private MyAsyncTask myAsyncTask;
private class MyAsyncTask extends AsyncTask<String,Integer,String>{
private String url,method,string;
public MyAsyncTask(String url,String method,String string){
this.url=url;
this.method=method;
this.string=string;
}
//在子线程里运行
@Override
protected String doInBackground(String... strings) {
String message="";
try {
URL mUrl=new URL(url);
HttpURLConnection connection= (HttpURLConnection) mUrl.openConnection();
connection.setRequestMethod(method);
connection.setConnectTimeout(5000);
if("POST".equals(method)){
PrintWriter printWriter=new PrintWriter(connection.getOutputStream());
printWriter.write(string);
printWriter.flush();
printWriter.close();
}
connection.connect();
int code=connection.getResponseCode();
if(code==HttpURLConnection.HTTP_OK){
InputStream inputStream=connection.getInputStream();
String data=convertStream2String(inputStream);
message=data;
}else{
message="0";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return message;
}
//在主线程里设置方法
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if("0".equals(s)){//失败
listener.fail();
}else{
listener.success(s);
}
}
}
//流转字符串
private String convertStream2String(InputStream input){
ByteArrayOutputStream baos = new ByteArrayOutputStream();// 自带缓存的输出流
int len=-1;
byte [] buffer = new byte[512];
try {
while((len = input.read(buffer))!=-1){
baos.write(buffer, 0, len); // 将读到的字节,写入baos
}
return new String(baos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private HttpListener listener;
//传递接口
public void result(HttpListener listener){
this.listener=listener;
}
public interface HttpListener{
void success(String data);
void fail();
}
}