List of usage examples for org.apache.commons.httpclient HttpMethod setDoAuthentication
public abstract void setDoAuthentication(boolean paramBoolean);
From source file:org.sonar.report.pdf.util.SonarAccess.java
public Document getUrlAsDocument(String urlPath) throws HttpException, IOException, DocumentException { HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(this.sonarUrl + urlPath); int status = 0; Logger.debug("HTTP Request: " + this.sonarUrl + urlPath); if (this.username != null) { Logger.debug("Setting authentication with username: " + this.username); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(new AuthScope(this.host, this.port), new UsernamePasswordCredentials(this.username, this.password)); method.setDoAuthentication(true); }//w ww . j a va 2s . c o m status = client.executeMethod(method); if (!(status == HttpStatus.SC_OK)) { Logger.error("Cant access to Sonar or project doesn't exist on Sonar instance. HTTP KO to " + this.sonarUrl + urlPath); throw new IOException("Cant access to Sonar or project doesn't exist on Sonar instance."); } Logger.debug("Received response."); SAXReader reader = new SAXReader(); return reader.read(method.getResponseBodyAsStream()); }
From source file:org.wso2.carbon.mashup.javascript.hostobjects.pooledhttpclient.PooledHttpClientHostObject.java
/** * Used by jsFunction_executeMethod()./*ww w .j av a 2 s . c o m*/ * * @param httpClient * @param contentType * @param charset * @param methodName * @param content * @param params */ private static void setParams(PooledHttpClientHostObject httpClient, HttpMethod method, String contentType, String charset, String methodName, Object content, NativeObject params) { // other parameters have been set, they are properly set to the // corresponding context if (ScriptableObject.getProperty(params, "cookiePolicy") instanceof String) { method.getParams().setCookiePolicy((String) ScriptableObject.getProperty(params, "cookiePolicy")); } else if (!ScriptableObject.getProperty(params, "cookiePolicy").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (ScriptableObject.getProperty(params, "contentType") instanceof String) { contentType = (String) ScriptableObject.getProperty(params, "contentType"); } else if (!ScriptableObject.getProperty(params, "contentType").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (ScriptableObject.getProperty(params, "charset") instanceof String) { charset = (String) ScriptableObject.getProperty(params, "charset"); } else if (!ScriptableObject.getProperty(params, "charset").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (ScriptableObject.getProperty(params, "timeout") instanceof Integer) { method.getParams().setSoTimeout((Integer) ScriptableObject.getProperty(params, "timeout")); } else if (!ScriptableObject.getProperty(params, "timeout").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (ScriptableObject.getProperty(params, "doAuthentication") instanceof Boolean) { method.setDoAuthentication((Boolean) ScriptableObject.getProperty(params, "doAuthentication")); } else if (!ScriptableObject.getProperty(params, "doAuthentication").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (ScriptableObject.getProperty(params, "followRedirect") instanceof Boolean) { method.setFollowRedirects((Boolean) ScriptableObject.getProperty(params, "followRedirect")); } else if (!ScriptableObject.getProperty(params, "followRedirect").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (methodName.equals("POST")) { // several parameters are specific to POST method if (ScriptableObject.getProperty(params, "contentChunked") instanceof Boolean) { boolean chuncked = (Boolean) ScriptableObject.getProperty(params, "contentChunked"); ((PostMethod) method).setContentChunked(chuncked); if (chuncked && content != null) { // if contentChucked is set true, then // InputStreamRequestEntity or // MultipartRequestEntity is used if (content instanceof String) { // InputStreamRequestEntity for string content ((PostMethod) method).setRequestEntity(new InputStreamRequestEntity( new ByteArrayInputStream(((String) content).getBytes()))); } else { // MultipartRequestEntity for Name-Value pair // content NativeObject element; List<StringPart> parts = new ArrayList<StringPart>(); String eName; String eValue; // create pairs using name-value pairs for (int i = 0; i < ((NativeArray) content).getLength(); i++) { if (((NativeArray) content).get(i, (NativeArray) content) instanceof NativeObject) { element = (NativeObject) ((NativeArray) content).get(i, (NativeArray) content); if (ScriptableObject.getProperty(element, "name") instanceof String && ScriptableObject.getProperty(element, "value") instanceof String) { eName = (String) ScriptableObject.getProperty(element, "name"); eValue = (String) ScriptableObject.getProperty(element, "value"); parts.add(new StringPart(eName, eValue)); } else { throw new RuntimeException("Invalid content definition, objects of the content" + " array should consists with strings for both key/value"); } } else { throw new RuntimeException( "Invalid content definition, content array should contain " + "Javascript Objects"); } } ((PostMethod) method).setRequestEntity(new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), method.getParams())); } } } else if (ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND) && content != null) { // contentChunking has not used if (content instanceof String) { try { ((PostMethod) method) .setRequestEntity(new StringRequestEntity((String) content, contentType, charset)); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unsupported Charset"); } } else { NativeObject element; List<NameValuePair> pairs = new ArrayList<NameValuePair>(); String eName; String eValue; // create pairs using name-value pairs for (int i = 0; i < ((NativeArray) content).getLength(); i++) { if (((NativeArray) content).get(i, (NativeArray) content) instanceof NativeObject) { element = (NativeObject) ((NativeArray) content).get(i, (NativeArray) content); if (ScriptableObject.getProperty(element, "name") instanceof String && ScriptableObject.getProperty(element, "value") instanceof String) { eName = (String) ScriptableObject.getProperty(element, "name"); eValue = (String) ScriptableObject.getProperty(element, "value"); pairs.add(new NameValuePair(eName, eValue)); } else { throw new RuntimeException( "Invalid content definition, objects of the content array " + "should consists with strings for both key/value"); } } else { throw new RuntimeException("Invalid content definition, content array should contain " + "Javascript Objects"); } } ((PostMethod) method).setRequestBody(pairs.toArray(new NameValuePair[pairs.size()])); } } else if (!ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } } else if (methodName.equals("GET")) { // here, the method now is GET if (content != null) { if (content instanceof String) { method.setQueryString((String) content); } else { NativeObject element; List<NameValuePair> pairs = new ArrayList<NameValuePair>(); String eName; String eValue; // create pairs using name-value pairs for (int i = 0; i < ((NativeArray) content).getLength(); i++) { if (((NativeArray) content).get(i, (NativeArray) content) instanceof NativeObject) { element = (NativeObject) ((NativeArray) content).get(i, (NativeArray) content); if (ScriptableObject.getProperty(element, "name") instanceof String && ScriptableObject.getProperty(element, "value") instanceof String) { eName = (String) ScriptableObject.getProperty(element, "name"); eValue = (String) ScriptableObject.getProperty(element, "value"); pairs.add(new NameValuePair(eName, eValue)); } else { throw new RuntimeException( "Invalid content definition, objects of the content array " + "should consists with strings for both key/value"); } } else { throw new RuntimeException("Invalid content definition, content array should contain " + "Javascript Objects"); } } method.setQueryString(pairs.toArray(new NameValuePair[pairs.size()])); } } } else if (methodName.equals("PUT")) { // several parameters are specific to PUT method if (ScriptableObject.getProperty(params, "contentChunked") instanceof Boolean) { boolean chuncked = (Boolean) ScriptableObject.getProperty(params, "contentChunked"); ((PutMethod) method).setContentChunked(chuncked); if (chuncked && content != null) { // if contentChucked is set true, then // InputStreamRequestEntity or // MultipartRequestEntity is used if (content instanceof String) { // InputStreamRequestEntity for string content ((PostMethod) method).setRequestEntity(new InputStreamRequestEntity( new ByteArrayInputStream(((String) content).getBytes()))); } else { throw new RuntimeException( "Invalid content definition, content should be a string when PUT " + "method is used"); } } } else if (ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND) && content != null) { // contentChunking has not used if (content instanceof String) { try { ((PostMethod) method) .setRequestEntity(new StringRequestEntity((String) content, contentType, charset)); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unsupported Charset"); } } else { throw new RuntimeException( "Invalid content definition, content should be a string when PUT " + "method is used"); } } else if (!ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } } // check whether preemptive authentication is used if (ScriptableObject.getProperty(params, "preemptiveAuth") instanceof Boolean) { httpClient.httpClient.getParams() .setAuthenticationPreemptive((Boolean) ScriptableObject.getProperty(params, "preemptiveAuth")); } else if (!ScriptableObject.getProperty(params, "preemptiveAuth").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } }
From source file:pukiwikiCommunicator.connector.SaveButtonDebugFrame.java
private String connectToURL(String url) { this.println("connectButton.actionPerformed, url=" + url); //TODO add your code for connectButton.actionPerformed String pageText = null;/*from ww w.j av a 2s .c o m*/ client = new HttpClient(); // this.messageTextArea.append(url+"\n"); String urlWithoutParameters = ""; if (authDialog != null) { this.println("authDialog is not null"); urlWithoutParameters = getUrlWithoutParameters(url); String registeredUrl = authDialog.getProperty("auth-url"); this.println("urlWithoutParamaters=" + urlWithoutParameters); this.println("registeredUrl=" + registeredUrl); if (registeredUrl == null) { this.authDialog = null; pageText = this.connectToURL(url); return pageText; } if (registeredUrl.equals(urlWithoutParameters)) { this.println("registeredUrl == urlWithoutParameters"); client.getParams().setAuthenticationPreemptive(true); // F?([UpX[h)??. String uname = authDialog.getID(); char[] pwd = authDialog.getPassword(); String pwdx = new String(pwd); String idPass = uname + ":" + pwdx; String authUrl = "basicAuth-" + urlWithoutParameters; this.setting.setProperty(authUrl, idPass); // Credentials defaultcreds1 = new UsernamePasswordCredentials(uname, pwdx); Credentials defaultcreds1 = new UsernamePasswordCredentials(idPass); // FXR[v. AuthScope scope1 = new AuthScope(null, -1, null); // XR[vF?gZbg. client.getState().setCredentials(scope1, defaultcreds1); } else { this.authDialog = null; pageText = this.connectToURL(url); return pageText; } } try { this.println("new getMethiod(" + url + ")"); HttpMethod method = new GetMethod(url); // method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, // new DefaultHttpMethodRetryHandler(3, false)); if (this.authDialog != null) { method.setDoAuthentication(true); } // method.getParams().setContentCharset("UTF-8"); int status = client.executeMethod(method); if (status != HttpStatus.SC_OK) { this.println("Method failed: " + method.getStatusLine()); if ((method.getStatusLine()).toString().indexOf("401") >= 0) { this.authDialog = new AuthDialog(this); this.authInputFlag = false; urlWithoutParameters = getUrlWithoutParameters(url); this.authDialog.setProperty("auth-url", urlWithoutParameters); this.println("before waitUntilMessageIsReturned"); // this.authDialog.start(); this.authDialog.setVisible(true); if (this.setting != null) { urlWithoutParameters = getUrlWithoutParameters(url); String authUrl = "basicAuth-" + urlWithoutParameters; String idPass = this.setting.getProperty(authUrl); StringTokenizer st1 = new StringTokenizer(idPass, ":"); String id = ""; String pas = ""; if (st1 != null) { id = st1.nextToken(); pas = st1.nextToken(); if (id != null) this.authDialog.setID(id); if (pas != null) this.authDialog.setPassword(pas); } } this.waitUntilMessageIsReturned(); //!! // this.authDialog.stop(); //!! this.authDialog.setVisible(false); this.println("after waitUntilMessageIsReturned"); if (this.loginButtonPressed) { this.println("loginButtonPressed"); pageText = this.connectToURL(url); } return pageText; } } else { pageText = this.getText(method); /* // String txt=method.getResponseBodyAsString(); InputStream is=method.getResponseBodyAsStream(); InputStreamReader isr=new InputStreamReader(is,this.charset); // InputStreamReader isr=new InputStreamReader(is,"UTF-8"); // InputStreamReader isr=new InputStreamReader(is); BufferedReader br=new BufferedReader(isr); String line=""; pageText=""; while(true){ line=br.readLine(); pageText=pageText+line+"\n"; if(line==null) break; this.messageTextArea.append(line+"\n"); // System.out.println(line); } */ } } catch (Exception e) { this.println(e.toString() + "\n"); e.printStackTrace(); return null; } return pageText; }
From source file:smilehouse.opensyncro.defaultcomponents.http.HTTPUtils.java
/** * Makes a HTTP request to the specified url with a set of parameters, * request method, user name and password * // www .j a va 2s .c o m * @param url the <code>URL</code> to make a request to * @param method either "GET", "POST", "PUT" or "SOAP" * @param parameters two dimensional string array containing parameters to send in the request * @param user user name to submit in the request * @param password password to submit in the request * @param charsetName charset name used for message content encoding * @param responseCharsetName charset name used to decode HTTP responses, * or null to use default ("ISO-8859-1") * @param contentType Content-Type header value (without charset information) * for POST (and SOAP) type requests. If null, defaults to * "text/xml". * @return a string array containing the body of the response, the headers of * the response and possible error message * @throws Exception */ public static HTTPResponse makeRequest(URL url, String method, String[][] parameters, String user, String password, String charsetName, String responseCharsetName, String contentType) throws Exception { HttpClient httpclient = new HttpClient(); HttpMethod request_method = null; HTTPResponse responseData = new HTTPResponse(); NameValuePair[] names_values = null; String requestContentType; if (contentType != null && contentType.length() > 0) { requestContentType = contentType; } else { requestContentType = DEFAULT_CONTENT_TYPE; } if (parameters != null && method.equals("PUT") == false) { names_values = new NameValuePair[parameters.length]; for (int i = 0; i < parameters.length; i++) { names_values[i] = new NameValuePair(parameters[i][0], parameters[i][1]); } } if (method.equalsIgnoreCase("POST")) { request_method = new PostMethod(url.toString()); if (names_values != null) ((PostMethod) request_method).setRequestBody(names_values); } else if (method.equalsIgnoreCase("PUT")) { if (parameters == null) throw new Exception("No data to use in PUT request"); request_method = new PutMethod(url.toString()); StringRequestEntity sre = new StringRequestEntity(parameters[0][0]); ((PutMethod) request_method).setRequestEntity(sre); } else if (method.equalsIgnoreCase("SOAP")) { String urlString = url.toString() + "?"; String message = null; String action = null; for (int i = 0; i < parameters.length; i++) { if (parameters[i][0].equals(SOAPMESSAGE)) message = parameters[i][1]; else if (parameters[i][0].equals(SOAP_ACTION_HEADER)) action = parameters[i][1]; else urlString += parameters[i][0] + "=" + parameters[i][1] + "&"; } urlString = urlString.substring(0, urlString.length() - 1); request_method = new PostMethod(urlString); // Encoding content with requested charset StringRequestEntity sre = new StringRequestEntity(message, requestContentType, charsetName); ((PostMethod) request_method).setRequestEntity(sre); if (action != null) { request_method.setRequestHeader(SOAP_ACTION_HEADER, action); } // Adding charset also into header's Content-Type request_method.addRequestHeader(CONTENT_TYPE_HEADER, requestContentType + "; charset=" + charsetName); } else { request_method = new GetMethod(url.toString()); if (names_values != null) ((GetMethod) request_method).setQueryString(names_values); } user = (user == null || user.length() < 1) ? null : user; password = (password == null || password.length() < 1) ? null : password; if ((user != null & password == null) || (user == null & password != null)) { throw new Exception("Invalid username or password"); } if (user != null && password != null) { httpclient.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(user, password); httpclient.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds); request_method.setDoAuthentication(true); } try { httpclient.executeMethod(request_method); if (request_method.getStatusCode() != HttpStatus.SC_OK) { responseData .setResponseError(request_method.getStatusCode() + " " + request_method.getStatusText()); } //Write response header to the out string array Header[] headers = request_method.getResponseHeaders(); responseData.appendToHeaders("\nHTTP status " + request_method.getStatusCode() + "\n"); for (int i = 0; i < headers.length; i++) { responseData.appendToHeaders(headers[i].getName() + ": " + headers[i].getValue() + "\n"); } /* * TODO: By default, the response charset should be read from the Content-Type header of * the response and that should be used in the InputStreamReader constructor: * * <code>new InputStreamReader(request_method.getResponseBodyAsStream(), * ((HttpMethodBase)request_method).getResponseCharSet());</code> * * But for backwards compatibility, the charset used by default is now the one that the * HttpClient library chooses (ISO-8859-1). An alternative charset can be chosen, but in * no situation is the charset read from the response's Content-Type header. */ BufferedReader br = null; if (responseCharsetName != null) { br = new BufferedReader( new InputStreamReader(request_method.getResponseBodyAsStream(), responseCharsetName)); } else { br = new BufferedReader(new InputStreamReader(request_method.getResponseBodyAsStream())); } String responseline; //Write response body to the out string array while ((responseline = br.readLine()) != null) { responseData.appendToBody(responseline + "\n"); } } finally { request_method.releaseConnection(); } return responseData; }