httpClient中java代码接口测试

/**
     * httpClient发送post请求
     * @param map  请求参数
     * @param url  请求远程地址
     * @author clc
     * @return
     */
    public static String httpClientPost(String url,Map<String,String> map){
        // 获取连接客户端工具
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String entityStr = null;
        CloseableHttpResponse response = null;
        try {
            // 创建POST请求对象
            HttpPost httpPost = new HttpPost(url);
            //参数封装对象
            List<NameValuePair> list = new LinkedList<>();

            for (Map.Entry<String,String> entry:map.entrySet()){
                list.add(new BasicNameValuePair( entry.getKey(), entry.getValue()));
            }
            // httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            // 使用URL实体转换工具
            UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
            httpPost.setEntity(entityParam);
            // 执行请求
            response = httpClient.execute(httpPost);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            entityStr = EntityUtils.toString(entity, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            // 释放连接
            if (null != response) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    System.err.println("释放连接出错");
                    e.printStackTrace();
                    return null;
                }
            }
        }
        return entityStr;
    }

    /**
     * httpClient发送get请求
     * @param map  请求参数
     * @param url  请求远程地址
     * @author clc
     * @return
     */
    public static String httpClientGet(String url,Map<String,String> map){
        // 获取连接客户端工具
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String entityStr = null;
        CloseableHttpResponse response = null;

        try {
            /*
             * 由于GET请求的参数都是拼装在URL地址后方,所以我们要构建一个URL,带参数
             */
            URIBuilder uriBuilder = new URIBuilder(url);
            /** 第一种添加参数的形式 */
            /*uriBuilder.addParameter("name", "root");
            uriBuilder.addParameter("password", "123456");*/
            /** 第二种添加参数的形式 */
            List<NameValuePair> list = new LinkedList<>();
            for (Map.Entry<String,String> entry:map.entrySet()){
                list.add(new BasicNameValuePair( entry.getKey(), entry.getValue()));
            }
            uriBuilder.setParameters(list);
            // 根据带参数的URI对象构建GET请求对象
            HttpGet httpGet = new HttpGet(uriBuilder.build());

            /*
             * 添加请求头信息
             */
            // 浏览器表示
           // httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
            // 传输的类型
            httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded");

            // 执行请求
            response = httpClient.execute(httpGet);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            entityStr = EntityUtils.toString(entity, "UTF-8");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            // 释放连接
            if (null != response) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }
        return entityStr;
    }

    /**
     * MultipartFile 转 File
     * @param file
     * @author clc
     * @throws Exception
     */
    public static File multipartFileToFile( @RequestParam MultipartFile file ) throws Exception {

        File toFile = null;
        if(file.equals("")||file.getSize()<=0){
            file = null;
        }else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    /**
     * File 转 MultipartFile
     * @param file
     * @author clc
     * @throws Exception
     */
    public static MultipartFile fileToMultipartFile( File file ) throws Exception {
        FileInputStream fileInput = new FileInputStream(file);
        MultipartFile toMultipartFile = new MockMultipartFile("file",file.getName(),"text/plain", IOUtils.toByteArray(fileInput));
        toMultipartFile.getInputStream();
        return toMultipartFile;
    }

    /**
     * 输入流转文件
     * @param ins
     * @author clc
     * @param file
     */
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
     /** 文件上传
     * @param url
     * @param file
     * @return
     */
    public static String httpClientUpload(String url,File file){
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String entityStr = "";
        try {
            HttpPost httppost = new HttpPost(url);

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build();
            httppost.setConfig(requestConfig);

            //文件
            FileBody bin = new FileBody(file);
            StringBody comment = new StringBody("This is comment", ContentType.TEXT_PLAIN);
            HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", bin).addPart("comment",comment).build();
            httppost.setEntity(reqEntity);

            //System.out.println("executing request " + httppost.getRequestLine());
            //执行请求
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                //协议状态码
                //System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();

                if (resEntity != null) {
                    // 使用Apache提供的工具类进行转换成字符串
                    entityStr = EntityUtils.toString(response.getEntity());
                    //System.out.println(responseEntityStr);
                    //System.out.println("Response content length: " + resEntity.getContentLength());
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        return entityStr;
    }

猜你喜欢

转载自blog.csdn.net/qq_41679695/article/details/88535769
今日推荐