httpclient3.0调用basic auth接口


    public static String httppost(String json,String url) {
        String username = "***";
        String password = "***";
        String result = "";
        try {
            HttpClient httpClient = new HttpClient();
            PostMethod postMethod = new PostMethod(url);
            //需要验证
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
            httpClient.getState().setCredentials(AuthScope.ANY, creds);
            StringRequestEntity requestEntity = new StringRequestEntity(json, "application/json", "UTF-8");
            postMethod.setRequestEntity(requestEntity);
            int i = httpClient.executeMethod(postMethod);
            InputStream inputStream = postMethod.getResponseBodyAsStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String s;
            StringBuffer sb = new StringBuffer();
            while ((s = br.readLine()) != null) {
                sb.append(s + "\n");
            }
            result = new String(sb.toString().getBytes(),"UTF-8");
            postMethod.releaseConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

你可能感兴趣的:(Java,json,java,开发语言)