HttpURLConnection使用

1. Get请求

    public static void get(String argUrl, Map params, Map headers) {
        try {
            String urlFromParams = createUrlFromParams(argUrl, params);

            URL url = new URL(urlFromParams);
            //得到connection对象。
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");

            if(headers != null){
                 for (Map.Entry entry : headers.entrySet()) {
                     connection.setRequestProperty(entry.getKey(), entry.getValue());
                 }
             }

            //连接
            connection.connect();
            //得到响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                StringBuilder sb = new StringBuilder();
                //得到响应流
                InputStream is = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));

                String line = "";
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
                is.close();
                connection.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

拼接参数

    /**
     * 将传递进来的参数拼接成 url
     **/
    public static String createUrlFromParams(String url, Map params) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append(url);
            if (url.indexOf('&') > 0 || url.indexOf('?') > 0) sb.append("&");
            else sb.append("?");
            for (Map.Entry urlParams : params.entrySet()) {
                String value = urlParams.getValue();
                //对参数进行 utf-8 编码,防止头信息传中文
                String urlValue = URLEncoder.encode(value, "UTF-8");
                sb.append(urlParams.getKey()).append("=").append(value).append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
        }
        return url;
    }

2.Post请求

    public static void post(String argUrl, String postData, Map headers) {
        try {
            URL url = new URL(argUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.connect();

            if(headers != null){
                 for (Map.Entry entry : headers.entrySet()) {
                     connection.setRequestProperty(entry.getKey(), entry.getValue());
                 }
             }

            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
            writer.write(postData);
            writer.close();

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                StringBuilder sb = new StringBuilder();
                //得到响应流
                InputStream is = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));

                String line = "";
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
                is.close();
                connection.disconnect();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

3.上传文件

    public void uploadFile(String argUrl,File file){
        try {
            URL url = new URL(argUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "file/*");//设置数据类型
            connection.connect();

            OutputStream outputStream = connection.getOutputStream();
            FileInputStream fileInputStream = new FileInputStream(file);//把文件封装成一个流
            int length = -1;
            byte[] bytes = new byte[1024];
            while ((length = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,length);//写的具体操作
            }
            fileInputStream.close();
            outputStream.close();

            int responseCode = connection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                StringBuilder sb = new StringBuilder();
                //得到响应流
                InputStream is = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));

                String line = "";
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
                is.close();
                connection.disconnect();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

上传文件(带参数)

    public void upload(String argUrl,Map params,File file){
        try{
            String BOUNDARY = java.util.UUID.randomUUID().toString();
            String TWO_HYPHENS = "--";
            String LINE_END = "\r\n";

            URL url = new URL(argUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);

            //设置请求头
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("Content-Type","multipart/form-data; BOUNDARY=" + BOUNDARY);
            connection.connect();

            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            StringBuffer strBufparam = new StringBuffer();

            if(params != null){
                for (Map.Entry entry : params.entrySet()) {
                    //封装键值对数据一
                    strBufparam.append(TWO_HYPHENS);
                    strBufparam.append(BOUNDARY);
                    strBufparam.append(LINE_END);
                    strBufparam.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"");
                    strBufparam.append(LINE_END);
                    strBufparam.append("Content-Type: " + "text/plain" );
                    strBufparam.append(LINE_END);
                    strBufparam.append("Content-Lenght: "+ entry.getValue().length());
                    strBufparam.append(LINE_END);
                    strBufparam.append(LINE_END);
                    strBufparam.append(entry.getValue());
                    strBufparam.append(LINE_END);
                    outputStream.write(strBufparam.toString().getBytes());
                }
            }
            //拼接文件的参数
            StringBuffer strBufFile = new StringBuffer();
            strBufFile.append(LINE_END);
            strBufFile.append(TWO_HYPHENS);
            strBufFile.append(BOUNDARY);
            strBufFile.append(LINE_END);
            strBufFile.append("Content-Disposition: form-data; name=\"" + "file" + "\"; filename=\"" + file.getName() + "\"");
            strBufFile.append(LINE_END);
            strBufFile.append("Content-Type: " + "file/*" );
            strBufFile.append(LINE_END);
            strBufFile.append("Content-Lenght: "+file.length());
            strBufFile.append(LINE_END);
            strBufFile.append(LINE_END);

            outputStream.write(strBufFile.toString().getBytes());

            //写入文件
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024*2];
            int length = -1;
            while ((length = fileInputStream.read(buffer)) != -1){
                outputStream.write(buffer,0,length);
            }
            outputStream.flush();
            fileInputStream.close();

            //写入标记结束位
            byte[] endData = (LINE_END + TWO_HYPHENS + BOUNDARY + TWO_HYPHENS + LINE_END).getBytes();//写结束标记位
            outputStream.write(endData);
            outputStream.flush();

            //得到响应
            int responseCode = connection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                StringBuilder sb = new StringBuilder();
                //得到响应流
                InputStream is = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));

                String line = "";
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
                is.close();
                connection.disconnect();
            }
        }catch (IOException e){

        }
    }

4.下载文件

    public static void download(String argUrl, String fileDir,String fileName) {
        try {
            URL url = new URL(argUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            int responseCode = connection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                InputStream inputStream = connection.getInputStream();
                File dir = new File(fileDir);
                if (!dir.exists()){
                    dir.mkdirs();
                }
                File file = new File(dir, fileName);//根据目录和文件名得到file对象
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buf = new byte[1024*8];
                int len = -1;
                while ((len = inputStream.read(buf)) != -1){
                    fos.write(buf, 0, len);
                }
                fos.flush();
                connection.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(HttpURLConnection使用)