Apache HttpComponents 运用

    public String sendRequest(String request, String url, String token) throws IOException {
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(request, "UTF-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("authorization", "Bearer " + token);
        HttpResponse httpResponse = httpclient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        InputStream is = httpEntity.getContent();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[2048];
        int bytesRead;
        try {
            while ((bytesRead = is.read(buffer, 0, 1024)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

        byte[] rep = baos.toByteArray();
        String reponse = new String(rep, "UTF-8");

        return reponse;
    }

猜你喜欢

转载自blog.csdn.net/qq_18357961/article/details/83958177