HttpURLConnection networking request tool class

Keywords: Java Android network

package com.example.abnerming.httputil.net;

import android.os.Handler;
import android.os.Message;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
*First, create a class (Helper) and construct
*Second, write a networking method, write get and post methods
*Third, make networking requests in get or post
*Fourth, after the request comes back, it is sent to the main thread through inter thread communication
*Fifth, write request interface success or failure or other
*Sixth, when the data returns or fails, call the interface
*
* */

public class Helper {
private final int HTTP_SUCCESS=100; / / success
private final int HTTP_FAIL=101; / / success

public Helper(){}


//get request
public Helper get(String url){
    doHttp(0,url,"");
    return this;
}

//Network request
private void doHttp(final int type, final String url, final String string){
    new Thread(){
        @Override
        public void run() {
            super.run();
            try {
                URL mUrl=new URL(url);
                HttpURLConnection connection= (HttpURLConnection)       mUrl.openConnection();
                String method="GET";
                if(type==1){
                    method="POST";
                }
                connection.setRequestMethod(method);//Set request method
                connection.setConnectTimeout(5000);//Set request timeout
                if(type==1){
                    //post request to add parameters
                    PrintWriter writer=new PrintWriter(connection.getOutputStream());
                    writer.write(string);
                    writer.flush();
                    writer.close();
                }


                connection.connect();
                int code=connection.getResponseCode();
                Message msg=Message.obtain();
                if(code==HttpURLConnection.HTTP_OK){
                    InputStream inputStream=connection.getInputStream();
                    String data=convertStream2String(inputStream);
                    msg.obj=data;
                    msg.what=HTTP_SUCCESS;
                }else{
                    msg.what=HTTP_FAIL;
                }

                handler.sendMessage(msg);

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.start();
}

private Handler handler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);

        switch (msg.what){
            case HTTP_SUCCESS://Success
               String data=(String) msg.obj;
                listener.success(data);
                break;
            case HTTP_FAIL://fail
                listener.fail();
                break;
        }
    }
};

//post request
public Helper post(String url,String string){
    doHttp(1,url,string);
    return this;
}


//Flow string
private   String convertStream2String(InputStream input){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();// Output stream with cache
    int len=-1;
    byte [] buffer = new byte[512];
    try {
        while((len = input.read(buffer))!=-1){
            baos.write(buffer, 0, len); // Write the bytes read to the BIOS
        }
        return new String(baos.toByteArray());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}


private HttpListener listener;
//Transfer interface
public void result(HttpListener listener){
    this.listener=listener;
}

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

}

Posted by varzosu on Sun, 05 Jan 2020 15:49:09 -0800