HttpURLConnection同步和异步请求,封装的一个网络工具类

本文介绍了一个使用HttpURLConnection实现的同步和异步网络请求工具类,方便进行HTTP请求操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class HttpHelper {

private HttpListener listener;
public HttpHelper(HttpListener listener){
    this.listener=listener;
}

//get请求
public HttpHelper get(String url){
    doHttp(url,"GET","");
    return this;
}
//post
public HttpHelper  post(String url,String string){
    doHttp(url,"POST",string);
    return this;
}

public void doHttp(String url,String method,String string){
    new MyAsyncTask(url,method,string).execute();
}


private class MyAsyncTask extends AsyncTask<String,Integer,String>{
    private String pathUrl,method,string;
    public MyAsyncTask(String pathUrl,String method,String string){
        this.pathUrl=pathUrl;
        this.method=method;
        this.string=string;
    }

    //在子线程里执行
    @Override
    protected String doInBackground(String... strings) {
        String data="";
        try {
            URL url=new URL(pathUrl);
            HttpURLConnection connection= (HttpURLConnection) url.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 is= connection.getInputStream();
                data=convertStream2String(is);
            }else{
                data="0";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return data;
    }


    //在主线程里执行
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if("0".equals(s)){//请求失败
            listener.fail();
        }else{
            listener.success(s);
        }

    }
}



public interface HttpListener{
    void success(String data);
    void fail();
}

public  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;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值