http post 模板 (设置header + json传参)

public static String postBody(String urlPath, String json, String tk) throws Exception {
        String body = "";
        URL url = new URL(urlPath);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        urlConnection.setRequestProperty("Authorization", "Bearer " + tk);
        try( OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());) {
            out.write(json);
            out.flush();
            InputStream inputStream = urlConnection.getInputStream();
            String encoding = urlConnection.getContentEncoding();
            body = IOUtils.toString(inputStream, encoding);
            if (urlConnection.getResponseCode() != 200 && urlConnection.getResponseCode() != 201) {
                throw new IOException() ;
            }
            return body;
        } catch (IOException e) {
           
        }
        return body;
    }   

你可能感兴趣的:(笔记)