Here you can find the source of executePostWithCredentials(String targetURL, String urlParameters, String userName, String password)
public static String executePostWithCredentials(String targetURL, String urlParameters, String userName, String password)
//package com.java2s; //License from project: Open Source License import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.Base64; public class Main { public static String executePostWithCredentials(String targetURL, String urlParameters, String userName, String password) {/*from w w w . ja v a 2 s . c o m*/ HttpURLConnection connection = null; try { //Create connection String userPassword = userName + ":" + password; String encoded = Base64.getEncoder().encodeToString(userPassword.getBytes("UTF-8")); URL url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Authorization", "Basic " + encoded); connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.close(); //Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); StringBuilder response = new StringBuilder(); // or StringBuffer if not Java 5+ String line; while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); if (response.length() == 0) { // if nothing is coming back, at least send the response code. // a correct commit only returns 200-ok response.append(connection.getResponseCode()); } return response.toString(); } catch (Exception e) { e.printStackTrace(); return null; } finally { if (connection != null) { connection.disconnect(); } } } }