Android Java Http get和post请求

首次发布:2020-10-08 11:13
public String get(String urlAddress) {
    try {
        URL url = new URL(urlAddress);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();//开启连接
        connection.connect();//连接服务器
        if (connection.getResponseCode() == 200) {
            //使用字符流形式进行回复
            InputStream is = connection.getInputStream();
            //读取信息BufferReader
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuffer buffer = new StringBuffer();
            String readLine = "";
            while ((readLine = reader.readLine()) != null) {
                buffer.append(readLine+"\r\n");
            }
            is.close();
            reader.close();
            connection.disconnect();
            return buffer.toString();
        } else {
            return "ERROR:"+connection.getResponseCode();
        }
    } catch (IOException e) {
        return e.toString();
    }
}


public String post(String urlAddress,String data ) {
    try {
        URL url = new URL(urlAddress);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //设置输入输出流
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");//设置为POST方法
        //开始设置请求头
        connection.setRequestProperty("Accept-Charset", "UTF-8");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.connect();//开始连接
        //以输出流的形式进行给服务器传输数据
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(data);
        outputStream.flush();
        outputStream.close();
        //服务器进行响应
        if (connection.getResponseCode() == 200) {
            InputStream is = connection.getInputStream();
            //读取信息
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuffer stringBuffer = new StringBuffer();//使用StringBuffer来存储所有信息
            String readLine = "";//使用readLine方法来存储整行信息
            while ((readLine = reader.readLine()) != null) {
                stringBuffer.append(readLine+"\r\n");
            }
            is.close();
            reader.close();
            connection.disconnect();
            return stringBuffer.toString();
        } else {
            //打印错误的信息
            return "ERROR:"+connection.getResponseCode();
        }
    } catch (IOException e) {
        return e.toString();
    }
}