List of usage examples for org.apache.commons.httpclient.methods PostMethod getRequestCharSet
public String getRequestCharSet()
From source file:com.pureinfo.force.net.impl.HttpUtilImpl.java
/** * @see com.pureinfo.force.net.IHttpUtil#getContent(String, NameValuePair[], * String, String)/*from w w w. j a v a 2 s. c o m*/ */ public String getContent(String _sUrl, NameValuePair[] _args, String _sRequestCharset, String _sResponseCharset) throws IOTransferException { if (_sRequestCharset == null) { _sRequestCharset = "utf-8"; } //1. to create http client and set proxy HttpClient client = new HttpClient(); if (m_proxyHost != null) { client.getHostConfiguration().setProxyHost(m_proxyHost); if (m_sProxyUser != null & m_sProxyPassword != null) { client.getState().setProxyCredentials(// new AuthScope(m_proxyHost.getHostName(), m_proxyHost.getPort()), new UsernamePasswordCredentials(m_sProxyUser, m_sProxyPassword)); } } //2. to create post PostMethod method = new PostMethod(_sUrl); if (m_nRetryCount > 0) { method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, // new DefaultHttpMethodRetryHandler(m_nRetryCount, false)); } method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + _sRequestCharset); for (int i = 0; _args != null && i < _args.length; i++) { method.addParameter(_args[i]); } //3. to send request and read response String sResponse; try { client.executeMethod(method); sResponse = method.getResponseBodyAsString(); if (!method.getRequestCharSet().equals(_sRequestCharset)) { sResponse = new String(sResponse.getBytes(), _sResponseCharset); } return sResponse; } catch (Exception ex) { throw new IOTransferException(_sUrl, ex); } finally { method.releaseConnection(); } }
From source file:com.sun.faban.driver.transport.hc3.ApacheHC3Transport.java
private void setParameters(PostMethod method, String request) throws UnsupportedEncodingException { // Check whether request is XML or JSON if (request.startsWith("<?xml") || request.startsWith("{")) { Header h = method.getRequestHeader("Content-Type"); if (h == null) { h = method.getRequestHeader("content-type"); }//from w w w. j a v a2 s. c om if (h != null) { method.setRequestEntity(new StringRequestEntity(request, h.getValue(), method.getRequestCharSet())); return; } } List<NameValuePair> parameters = new ArrayList<NameValuePair>(); // If none of both, just treat it as html. int idx = 0; if (request == null || request.length() == 0) return; if (request.charAt(0) == '?') ++idx; do { int endIdx = request.indexOf('&', idx); if (endIdx == -1) endIdx = request.length(); int eqIdx = request.indexOf('=', idx); if (eqIdx != -1 && eqIdx < endIdx) { parameters.add( new NameValuePair(request.substring(idx, eqIdx), request.substring(eqIdx + 1, endIdx))); } else { parameters.add(new NameValuePair(request.substring(idx, endIdx), null)); } idx = endIdx + 1; } while (idx < request.length()); method.addParameters(parameters.toArray(new NameValuePair[parameters.size()])); }
From source file:ome.formats.importer.util.HtmlMessenger.java
/** * Login to website//from w w w . j av a 2s. c o m * * @param url * @param username * @param password * @return * @throws HtmlMessengerException */ public String login(String url, String username, String password) throws HtmlMessengerException { String serverReply = ""; Reader reader = null; try { // Execute the POST method PostMethod loginMethod = new PostMethod(url); Part[] parts = { new StringPart("username", username), new StringPart("password", password) }; MultipartRequestEntity mpre = new MultipartRequestEntity(parts, loginMethod.getParams()); ProgressListener listener = new ProgressListener() { /* (non-Javadoc) * @see ome.formats.importer.util.FileUploadCounter.ProgressListener#update(long) */ public void update(long bytesRead) { } }; FileUploadCounter hfre = new FileUploadCounter(mpre, listener); loginMethod.setRequestEntity(hfre); int statusCode = client.executeMethod(loginMethod); if (statusCode != -1) { reader = new InputStreamReader(loginMethod.getResponseBodyAsStream(), loginMethod.getRequestCharSet()); char[] buf = new char[32678]; StringBuilder str = new StringBuilder(); for (int n; (n = reader.read(buf)) != -1;) str.append(buf, 0, n); loginMethod.releaseConnection(); serverReply = str.toString(); } return serverReply; } catch (Exception e) { throw new HtmlMessengerException("Cannot Connect", e); } finally { Utils.closeQuietly(reader); } }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java
private String sendPostData(PostMethod post) throws IOException { // Buffer to hold the post body, except file content StringBuilder postedBody = new StringBuilder(1000); HTTPFileArg[] files = getHTTPFiles(); // Check if we should do a multipart/form-data or an // application/x-www-form-urlencoded post request if (getUseMultipartForPost()) { // If a content encoding is specified, we use that as the // encoding of any parameter values String contentEncoding = getContentEncoding(); if (isNullOrEmptyTrimmed(contentEncoding)) { contentEncoding = null;//from w w w. j ava2s . c o m } final boolean browserCompatible = getDoBrowserCompatibleMultipart(); // We don't know how many entries will be skipped List<PartBase> partlist = new ArrayList<>(); // Create the parts // Add any parameters for (JMeterProperty jMeterProperty : getArguments()) { HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue(); String parameterName = arg.getName(); if (arg.isSkippable(parameterName)) { continue; } StringPart part = new StringPart(arg.getName(), arg.getValue(), contentEncoding); if (browserCompatible) { part.setTransferEncoding(null); part.setContentType(null); } partlist.add(part); } // Add any files for (HTTPFileArg file : files) { File inputFile = FileServer.getFileServer().getResolvedFile(file.getPath()); // We do not know the char set of the file to be uploaded, so we set it to null ViewableFilePart filePart = new ViewableFilePart(file.getParamName(), inputFile, file.getMimeType(), null); filePart.setCharSet(null); // We do not know what the char set of the file is partlist.add(filePart); } // Set the multipart for the post int partNo = partlist.size(); Part[] parts = partlist.toArray(new Part[partNo]); MultipartRequestEntity multiPart = new MultipartRequestEntity(parts, post.getParams()); post.setRequestEntity(multiPart); // Set the content type String multiPartContentType = multiPart.getContentType(); post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, multiPartContentType); // If the Multipart is repeatable, we can send it first to // our own stream, without the actual file content, so we can return it if (multiPart.isRepeatable()) { // For all the file multiparts, we must tell it to not include // the actual file content for (int i = 0; i < partNo; i++) { if (parts[i] instanceof ViewableFilePart) { ((ViewableFilePart) parts[i]).setHideFileData(true); // .sendMultipartWithoutFileContent(bos); } } // Write the request to our own stream ByteArrayOutputStream bos = new ByteArrayOutputStream(); multiPart.writeRequest(bos); bos.flush(); // We get the posted bytes using the encoding used to create it postedBody.append(new String(bos.toByteArray(), contentEncoding == null ? "US-ASCII" // $NON-NLS-1$ this is the default used by HttpClient : contentEncoding)); bos.close(); // For all the file multiparts, we must revert the hiding of // the actual file content for (int i = 0; i < partNo; i++) { if (parts[i] instanceof ViewableFilePart) { ((ViewableFilePart) parts[i]).setHideFileData(false); } } } else { postedBody.append("<Multipart was not repeatable, cannot view what was sent>"); // $NON-NLS-1$ } } else { // Check if the header manager had a content type header // This allows the user to specify his own content-type for a POST request Header contentTypeHeader = post.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE); boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null && contentTypeHeader.getValue().length() > 0; // If there are no arguments, we can send a file as the body of the request // TODO: needs a multiple file upload scenerio if (!hasArguments() && getSendFileAsPostBody()) { // If getSendFileAsPostBody returned true, it's sure that file is not null HTTPFileArg file = files[0]; if (!hasContentTypeHeader) { // Allow the mimetype of the file to control the content type if (file.getMimeType() != null && file.getMimeType().length() > 0) { post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType()); } else { post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED); } } FileRequestEntity fileRequestEntity = new FileRequestEntity(new File(file.getPath()), null); post.setRequestEntity(fileRequestEntity); // We just add placeholder text for file content postedBody.append("<actual file content, not shown here>"); } else { // In a post request which is not multipart, we only support // parameters, no file upload is allowed // If a content encoding is specified, we set it as http parameter, so that // the post body will be encoded in the specified content encoding String contentEncoding = getContentEncoding(); boolean haveContentEncoding = false; if (isNullOrEmptyTrimmed(contentEncoding)) { contentEncoding = null; } else { post.getParams().setContentCharset(contentEncoding); haveContentEncoding = true; } // If none of the arguments have a name specified, we // just send all the values as the post body if (getSendParameterValuesAsPostBody()) { // Allow the mimetype of the file to control the content type // This is not obvious in GUI if you are not uploading any files, // but just sending the content of nameless parameters // TODO: needs a multiple file upload scenerio if (!hasContentTypeHeader) { HTTPFileArg file = files.length > 0 ? files[0] : null; if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) { post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType()); } else { // TODO - is this the correct default? post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED); } } // Just append all the parameter values, and use that as the post body StringBuilder postBody = new StringBuilder(); for (JMeterProperty jMeterProperty : getArguments()) { HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue(); String value; if (haveContentEncoding) { value = arg.getEncodedValue(contentEncoding); } else { value = arg.getEncodedValue(); } postBody.append(value); } StringRequestEntity requestEntity = new StringRequestEntity(postBody.toString(), post.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE).getValue(), contentEncoding); post.setRequestEntity(requestEntity); } else { // It is a normal post request, with parameter names and values // Set the content type if (!hasContentTypeHeader) { post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED); } // Add the parameters for (JMeterProperty jMeterProperty : getArguments()) { HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue(); // The HTTPClient always urlencodes both name and value, // so if the argument is already encoded, we have to decode // it before adding it to the post request String parameterName = arg.getName(); if (arg.isSkippable(parameterName)) { continue; } String parameterValue = arg.getValue(); if (!arg.isAlwaysEncoded()) { // The value is already encoded by the user // Must decode the value now, so that when the // httpclient encodes it, we end up with the same value // as the user had entered. String urlContentEncoding = contentEncoding; if (urlContentEncoding == null || urlContentEncoding.length() == 0) { // Use the default encoding for urls urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING; } parameterName = URLDecoder.decode(parameterName, urlContentEncoding); parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding); } // Add the parameter, httpclient will urlencode it post.addParameter(parameterName, parameterValue); } /* // // Alternative implementation, to make sure that HTTPSampler and HTTPSampler2 // // sends the same post body. // // // Only include the content char set in the content-type header if it is not // // an APPLICATION_X_WWW_FORM_URLENCODED content type // String contentCharSet = null; // if(!post.getRequestHeader(HEADER_CONTENT_TYPE).getValue().equals(APPLICATION_X_WWW_FORM_URLENCODED)) { // contentCharSet = post.getRequestCharSet(); // } // StringRequestEntity requestEntity = new StringRequestEntity(getQueryString(contentEncoding), post.getRequestHeader(HEADER_CONTENT_TYPE).getValue(), contentCharSet); // post.setRequestEntity(requestEntity); */ } // If the request entity is repeatable, we can send it first to // our own stream, so we can return it if (post.getRequestEntity().isRepeatable()) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); post.getRequestEntity().writeRequest(bos); bos.flush(); // We get the posted bytes using the encoding used to create it postedBody.append(new String(bos.toByteArray(), post.getRequestCharSet())); bos.close(); } else { postedBody.append("<RequestEntity was not repeatable, cannot view what was sent>"); } } } // Set the content length post.setRequestHeader(HTTPConstants.HEADER_CONTENT_LENGTH, Long.toString(post.getRequestEntity().getContentLength())); return postedBody.toString(); }
From source file:org.eclipse.mylyn.tasks.tests.web.WebRepositoryConnectorTest.java
public void testEncodingParameters() throws Exception { TaskRepository repository = new TaskRepository(WebRepositoryConnector.REPOSITORY_TYPE, "http://foo.net"); repository.setAuthenticationCredentials("USER", "PASSWORD"); repository.setProperty(WebRepositoryConnector.PROPERTY_LOGIN_REQUEST_METHOD, WebRepositoryConnector.REQUEST_POST); repository.setProperty(WebRepositoryConnector.PROPERTY_LOGIN_REQUEST_URL, // "${serverUrl}/Login.php?xajax=xCheckUserLogin&xajaxargs[]=<xjxquery><q>${xjxquery}</q></xjxquery>"); repository.setProperty("param_xjxquery", "TestUserName=${userId}&TestUserPWD=${password}&HttpRefer="); Map<String, String> params = new HashMap<String, String>(); PostMethod method = (PostMethod) WebRepositoryConnector.getLoginMethod(params, repository); String form = EncodingUtil.formUrlEncode(method.getParameters(), method.getRequestCharSet()); assertEquals("xajax=xCheckUserLogin&" + // "xajaxargs%5B%5D=%3Cxjxquery%3E%3Cq%3E" + // "TestUserName%3DUSER%26" + // "TestUserPWD%3DPASSWORD%26" + // "HttpRefer%3D" + // "%3C%2Fq%3E%3C%2Fxjxquery%3E", form); }