List of usage examples for org.apache.commons.httpclient.methods.multipart StringPart StringPart
public StringPart(String paramString1, String paramString2, String paramString3)
From source file:de.michaeltamm.W3cMarkupValidator.java
/** * Validates the given <code>html</code>. * * @param html a complete HTML document/*from w ww . j av a 2s.co m*/ */ public W3cMarkupValidationResult validate(String html) { if (_httpClient == null) { final MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); _httpClient = new HttpClient(connectionManager); } final PostMethod postMethod = new PostMethod(_checkUrl); final Part[] data = { // The HTML to validate ... new StringPart("fragment", html, "UTF-8"), new StringPart("prefill", "0", "UTF-8"), new StringPart("doctype", "Inline", "UTF-8"), new StringPart("prefill_doctype", "html401", "UTF-8"), // List Messages Sequentially | Group Error Messages by Type ... new StringPart("group", "0", "UTF-8"), // Show source ... new StringPart("ss", "1", "UTF-8"), // Verbose Output ... new StringPart("verbose", "1", "UTF-8"), }; postMethod.setRequestEntity(new MultipartRequestEntity(data, postMethod.getParams())); try { final int status = _httpClient.executeMethod(postMethod); if (status != 200) { throw new RuntimeException(_checkUrl + " responded with " + status); } final String pathPrefix = _checkUrl.substring(0, _checkUrl.lastIndexOf('/') + 1); final String resultPage = getResponseBody(postMethod).replace("\"./", "\"" + pathPrefix) .replace("src=\"images/", "src=\"" + pathPrefix + "images/") .replace("<script type=\"text/javascript\" src=\"loadexplanation.js\">", "<script type=\"text/javascript\" src=\"" + pathPrefix + "loadexplanation.js\">"); return new W3cMarkupValidationResult(resultPage); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { postMethod.releaseConnection(); } }
From source file:com.boyuanitsm.pay.alipay.util.httpClient.HttpProtocolHandler.java
/** * Http//from www . j av a2 s. co m * * @param request ? * @param strParaFileName ??? * @param strFilePath * @return * @throws HttpException, IOException */ public HttpResponse execute(HttpRequest request, String strParaFileName, String strFilePath) throws HttpException, IOException { HttpClient httpclient = new HttpClient(connectionManager); // int connectionTimeout = defaultConnectionTimeout; if (request.getConnectionTimeout() > 0) { connectionTimeout = request.getConnectionTimeout(); } httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); // int soTimeout = defaultSoTimeout; if (request.getTimeout() > 0) { soTimeout = request.getTimeout(); } httpclient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout); // ConnectionManagerconnection httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout); String charset = request.getCharset(); charset = charset == null ? DEFAULT_CHARSET : charset; HttpMethod method = null; //get?? if (request.getMethod().equals(HttpRequest.METHOD_GET)) { method = new GetMethod(request.getUrl()); method.getParams().setCredentialCharset(charset); // parseNotifyConfig??GETrequestQueryString method.setQueryString(request.getQueryString()); } else if (strParaFileName.equals("") && strFilePath.equals("")) { //post?? method = new PostMethod(request.getUrl()); ((PostMethod) method).addParameters(request.getParameters()); method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; text/html; charset=" + charset); } else { //post? method = new PostMethod(request.getUrl()); List<Part> parts = new ArrayList<Part>(); for (int i = 0; i < request.getParameters().length; i++) { parts.add(new StringPart(request.getParameters()[i].getName(), request.getParameters()[i].getValue(), charset)); } //?strParaFileName??? parts.add(new FilePart(strParaFileName, new FilePartSource(new File(strFilePath)))); // ((PostMethod) method).setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[0]), new HttpMethodParams())); } // Http HeaderUser-Agent method.addRequestHeader("User-Agent", "Mozilla/4.0"); HttpResponse response = new HttpResponse(); try { httpclient.executeMethod(method); if (request.getResultType().equals(HttpResultType.STRING)) { response.setStringResult(method.getResponseBodyAsString()); } else if (request.getResultType().equals(HttpResultType.BYTES)) { response.setByteResult(method.getResponseBody()); } response.setResponseHeaders(method.getResponseHeaders()); } catch (UnknownHostException ex) { return null; } catch (IOException ex) { return null; } catch (Exception ex) { return null; } finally { method.releaseConnection(); } return response; }
From source file:greenfoot.export.mygame.MyGameClient.java
public final MyGameClient submit(String hostAddress, String uid, String password, String jarFileName, File sourceFile, File screenshotFile, int width, int height, ScenarioInfo info) throws UnknownHostException, IOException { String gameName = info.getTitle(); String shortDescription = info.getShortDescription(); String longDescription = info.getLongDescription(); String updateDescription = info.getUpdateDescription(); String gameUrl = info.getUrl(); HttpClient httpClient = getHttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(20 * 1000); // 20s timeout // Authenticate user and initiate session PostMethod postMethod = new PostMethod(hostAddress + "account/authenticate"); postMethod.addParameter("user[username]", uid); postMethod.addParameter("user[password]", password); int response = httpClient.executeMethod(postMethod); if (response == 407 && listener != null) { // proxy auth required String[] authDetails = listener.needProxyAuth(); if (authDetails != null) { String proxyHost = httpClient.getHostConfiguration().getProxyHost(); int proxyPort = httpClient.getHostConfiguration().getProxyPort(); AuthScope authScope = new AuthScope(proxyHost, proxyPort); Credentials proxyCreds = new UsernamePasswordCredentials(authDetails[0], authDetails[1]); httpClient.getState().setProxyCredentials(authScope, proxyCreds); // Now retry: response = httpClient.executeMethod(postMethod); }/* ww w . j a v a 2 s . c om*/ } if (response > 400) { error(Config.getString("export.publish.errorResponse") + " - " + response); return this; } // Check authentication result if (!handleResponse(postMethod)) { return this; } // Send the scenario and associated info List<String> tagsList = info.getTags(); boolean hasSource = sourceFile != null; //determining the number of parts to send through //use a temporary map holder Map<String, String> partsMap = new HashMap<String, String>(); if (info.isUpdate()) { partsMap.put("scenario[update_description]", updateDescription); } else { partsMap.put("scenario[long_description]", longDescription); partsMap.put("scenario[short_description]", shortDescription); } int size = partsMap.size(); if (screenshotFile != null) { size = size + 1; } //base number of parts is 6 int counter = 6; Part[] parts = new Part[counter + size + tagsList.size() + (hasSource ? 1 : 0)]; parts[0] = new StringPart("scenario[title]", gameName, "UTF-8"); parts[1] = new StringPart("scenario[main_class]", "greenfoot.export.GreenfootScenarioViewer", "UTF-8"); parts[2] = new StringPart("scenario[width]", "" + width, "UTF-8"); parts[3] = new StringPart("scenario[height]", "" + height, "UTF-8"); parts[4] = new StringPart("scenario[url]", gameUrl, "UTF-8"); parts[5] = new ProgressTrackingPart("scenario[uploaded_data]", new File(jarFileName), this); Iterator<String> mapIterator = partsMap.keySet().iterator(); String key = ""; String obj = ""; while (mapIterator.hasNext()) { key = mapIterator.next().toString(); obj = partsMap.get(key).toString(); parts[counter] = new StringPart(key, obj, "UTF-8"); counter = counter + 1; } if (hasSource) { parts[counter] = new ProgressTrackingPart("scenario[source_data]", sourceFile, this); counter = counter + 1; } if (screenshotFile != null) { parts[counter] = new ProgressTrackingPart("scenario[screenshot_data]", screenshotFile, this); counter = counter + 1; } int tagNum = 0; for (Iterator<String> i = tagsList.iterator(); i.hasNext();) { parts[counter] = new StringPart("scenario[tag" + tagNum++ + "]", i.next()); counter = counter + 1; } postMethod = new PostMethod(hostAddress + "upload-scenario"); postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); response = httpClient.executeMethod(postMethod); if (response > 400) { error(Config.getString("export.publish.errorResponse") + " - " + response); return this; } if (!handleResponse(postMethod)) { return this; } // Done. listener.uploadComplete(new PublishEvent(PublishEvent.STATUS)); return this; }
From source file:fr.eurecom.nerd.core.proxy.ExtractivClient.java
private static PostMethod getExtractivProcessString(final URI extractivURI, final String content, final String serviceKey) throws FileNotFoundException { final PartBase filePart = new StringPart("content", content, null); // bytes to upload final ArrayList<Part> message = new ArrayList<Part>(); message.add(filePart);/*from w ww . j a v a 2 s . co m*/ message.add(new StringPart("formids", "content")); message.add(new StringPart("output_format", "JSON")); message.add(new StringPart("api_key", serviceKey)); final Part[] messageArray = message.toArray(new Part[0]); // Use a Post for the file upload final PostMethod postMethod = new PostMethod(extractivURI.toString()); postMethod.setRequestEntity(new MultipartRequestEntity(messageArray, postMethod.getParams())); postMethod.addRequestHeader("Accept-Encoding", "gzip"); // Request the response be compressed (this is highly recommended) return postMethod; }
From source file:net.sf.antcontrib.net.httpclient.PostMethodTask.java
protected void configureMethod(HttpMethodBase method) { PostMethod post = (PostMethod) method; if (parts.size() == 1 && !multipart) { Object part = parts.get(0); if (part instanceof FilePartType) { FilePartType filePart = (FilePartType) part; try { stream = new FileInputStream(filePart.getPath().getAbsolutePath()); post.setRequestEntity(new InputStreamRequestEntity(stream, filePart.getPath().length(), filePart.getContentType())); } catch (IOException e) { throw new BuildException(e); }/*from w w w . j a va 2 s .c o m*/ } else if (part instanceof TextPartType) { TextPartType textPart = (TextPartType) part; try { post.setRequestEntity(new StringRequestEntity(textPart.getValue(), textPart.getContentType(), textPart.getCharSet())); } catch (UnsupportedEncodingException e) { throw new BuildException(e); } } } else if (!parts.isEmpty()) { Part partArray[] = new Part[parts.size()]; for (int i = 0; i < parts.size(); i++) { Object part = parts.get(i); if (part instanceof FilePartType) { FilePartType filePart = (FilePartType) part; try { partArray[i] = new FilePart(filePart.getPath().getName(), filePart.getPath().getName(), filePart.getPath(), filePart.getContentType(), filePart.getCharSet()); } catch (FileNotFoundException e) { throw new BuildException(e); } } else if (part instanceof TextPartType) { TextPartType textPart = (TextPartType) part; partArray[i] = new StringPart(textPart.getName(), textPart.getValue(), textPart.getCharSet()); ((StringPart) partArray[i]).setContentType(textPart.getContentType()); } } MultipartRequestEntity entity = new MultipartRequestEntity(partArray, post.getParams()); post.setRequestEntity(entity); } }
From source file:cn.newtouch.util.HttpClientUtil.java
/** * //from w w w .j a v a2 s . co m * * * @since 2012-1-8 * @param url * URL?URL? * @param file * * @param fileFieldName * forminputname * * @param params * ??? * @throws Exception */ public static void uploadFile(String url, File file, String fileFieldName, Map<String, String> params) throws Exception { String targetURL = url;// URL File targetFile = file;// PostMethod filePost = new PostMethod(targetURL); try { List<StringPart> strPartList = new ArrayList<StringPart>(); // ??? Set<String> keys = params.keySet(); for (String key : keys) { StringPart sp = new StringPart(key, params.get(key), "utf-8"); strPartList.add(sp); } Part[] parts = new Part[1 + strPartList.size()]; parts[0] = new FilePart(fileFieldName, targetFile); for (int i = 0; i < strPartList.size(); i++) { parts[i + 1] = strPartList.get(i); } filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { System.out.println("?"); // ? } else { System.out.println(""); throw new Exception("?" + status); // } } catch (Exception e) { e.printStackTrace(); throw new Exception("" + e.getMessage()); } finally { filePost.releaseConnection(); } }
From source file:info.magnolia.cms.filters.MultipartRequestFilterTempFileDeletionTest.java
private MultipartRequestEntity newMultipartRequestEntity() throws Exception { PostMethod method = new PostMethod(); Part[] parts = { new StringPart("param1", "value1", "UTF-8"), new StringPart("param2", "", "UTF-8"), new StringPart("param3", "value3a", "UTF-8"), new StringPart("param3", "value3b", "UTF-8"), new FilePart("document", testFile, "text/xml", "UTF-8") }; return new MultipartRequestEntity(parts, method.getParams()); }
From source file:at.gv.egiz.bku.binding.DataUrlConnectionImpl.java
@Override public void transmit(SLResult slResult) throws IOException { log.trace("Sending data."); if (urlEncoded) { ///*from ww w . j a v a2 s . c o m*/ // application/x-www-form-urlencoded (legacy, SL < 1.2) // OutputStream os = connection.getOutputStream(); OutputStreamWriter streamWriter = new OutputStreamWriter(os, HttpUtil.DEFAULT_CHARSET); // ResponseType streamWriter.write(FORMPARAM_RESPONSETYPE); streamWriter.write("="); streamWriter.write(URLEncoder.encode(DEFAULT_RESPONSETYPE, "UTF-8")); streamWriter.write("&"); // XMLResponse / Binary Response if (slResult.getResultType() == SLResultType.XML) { streamWriter.write(DataUrlConnection.FORMPARAM_XMLRESPONSE); } else { streamWriter.write(DataUrlConnection.FORMPARAM_BINARYRESPONSE); } streamWriter.write("="); streamWriter.flush(); URLEncodingWriter urlEnc = new URLEncodingWriter(streamWriter); slResult.writeTo(new StreamResult(urlEnc), false); urlEnc.flush(); // transfer parameters char[] cbuf = new char[512]; int len; for (HTTPFormParameter formParameter : httpFormParameter) { streamWriter.write("&"); streamWriter.write(URLEncoder.encode(formParameter.getName(), "UTF-8")); streamWriter.write("="); InputStreamReader reader = new InputStreamReader(formParameter.getData(), (formParameter.getCharSet() != null) ? formParameter.getCharSet() : "UTF-8"); // assume request was // application/x-www-form-urlencoded, // formParam therefore UTF-8 while ((len = reader.read(cbuf)) != -1) { urlEnc.write(cbuf, 0, len); } urlEnc.flush(); } streamWriter.close(); } else { // // multipart/form-data (conforming to SL 1.2) // ArrayList<Part> parts = new ArrayList<Part>(); // ResponseType StringPart responseType = new StringPart(FORMPARAM_RESPONSETYPE, DEFAULT_RESPONSETYPE, "UTF-8"); responseType.setTransferEncoding(null); parts.add(responseType); // XMLResponse / Binary Response SLResultPart slResultPart = new SLResultPart(slResult, XML_RESPONSE_ENCODING); if (slResult.getResultType() == SLResultType.XML) { slResultPart.setTransferEncoding(null); slResultPart.setContentType(slResult.getMimeType()); slResultPart.setCharSet(XML_RESPONSE_ENCODING); } else { slResultPart.setTransferEncoding(null); slResultPart.setContentType(slResult.getMimeType()); } parts.add(slResultPart); // transfer parameters for (HTTPFormParameter formParameter : httpFormParameter) { InputStreamPartSource source = new InputStreamPartSource(null, formParameter.getData()); FilePart part = new FilePart(formParameter.getName(), source, formParameter.getContentType(), formParameter.getCharSet()); part.setTransferEncoding(formParameter.getTransferEncoding()); parts.add(part); } OutputStream os = connection.getOutputStream(); Part.sendParts(os, parts.toArray(new Part[parts.size()]), boundary.getBytes()); os.close(); } // MultipartRequestEntity PostMethod InputStream is = null; try { is = connection.getInputStream(); } catch (IOException iox) { log.info("Failed to get InputStream of HTTPUrlConnection.", iox); } log.trace("Reading response."); response = new DataUrlResponse(url.toString(), connection.getResponseCode(), is); Map<String, String> responseHttpHeaders = new HashMap<String, String>(); Map<String, List<String>> httpHeaders = connection.getHeaderFields(); for (Iterator<String> keyIt = httpHeaders.keySet().iterator(); keyIt.hasNext();) { String key = keyIt.next(); StringBuffer value = new StringBuffer(); for (String val : httpHeaders.get(key)) { value.append(val); value.append(HttpUtil.SEPARATOR[0]); } String valString = value.substring(0, value.length() - 1); if ((key != null) && (value.length() > 0)) { responseHttpHeaders.put(key, valString); } } response.setResponseHttpHeaders(responseHttpHeaders); }
From source file:com.ihelpoo.app.api.ApiClient.java
/** * post/*from ww w . j av a 2 s . c o m*/ * * @param url * @param params * @param files * @throws AppException */ private static InputStream _post(AppContext appContext, String url, Map<String, Object> params, Map<String, File> files) throws AppException { //System.out.println("post_url==> "+url); String cookie = getCookie(appContext); String userAgent = getUserAgent(appContext); HttpClient httpClient = null; PostMethod httpPost = null; //post??? int length = (params == null ? 0 : params.size()) + (files == null ? 0 : files.size()); Part[] parts = new Part[length]; int i = 0; if (params != null) for (String name : params.keySet()) { parts[i++] = new StringPart(name, String.valueOf(params.get(name)), UTF_8); } if (files != null) for (String file : files.keySet()) { try { parts[i++] = new FilePart(file, files.get(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } //System.out.println("post_key_file==> "+file); } String responseBody = ""; int time = 0; do { try { httpClient = getHttpClient(); httpPost = getHttpPost(url, cookie, userAgent); httpPost.setRequestEntity(new MultipartRequestEntity(parts, httpPost.getParams())); int statusCode = httpClient.executeMethod(httpPost); if (statusCode != HttpStatus.SC_OK) { throw AppException.http(statusCode); } else if (statusCode == HttpStatus.SC_OK) { Cookie[] cookies = httpClient.getState().getCookies(); String tmpcookies = ""; for (Cookie ck : cookies) { tmpcookies += ck.toString() + ";"; } //?cookie if (appContext != null && tmpcookies != "") { appContext.setProperty("cookie", tmpcookies); appCookie = tmpcookies; } } responseBody = httpPost.getResponseBodyAsString(); // System.out.println("XMLDATA=====>"+responseBody); break; } catch (HttpException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } // ????? e.printStackTrace(); throw AppException.http(e); } catch (IOException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } // ? e.printStackTrace(); throw AppException.network(e); } finally { // httpPost.releaseConnection(); httpClient = null; } } while (time < RETRY_TIME); responseBody = responseBody.replaceAll("\\p{Cntrl}", ""); // if(responseBody.contains("result") && responseBody.contains("errorCode") && appContext.containsProperty("user.uid")){//FIXME // try { // Result res = Result.parse(new ByteArrayInputStream(responseBody.getBytes())); // if(res.getErrorCode() == 0){ // appContext.logout(); // appContext.getUnLoginHandler().sendEmptyMessage(1); // } // } catch (Exception e) { // e.printStackTrace(); // } // } return new ByteArrayInputStream(responseBody.getBytes()); }
From source file:net.exclaimindustries.geohashdroid.wiki.WikiUtils.java
/** Uploads an image to the wiki @param httpclient an active HTTP session, wiki login has to have happened before. @param filename the name of the new image file @param description the description of the image. An initial description will be used as page content for the image's wiki page @param formfields a formfields hash as modified by getWikiPage containing an edittoken we can use (see the MediaWiki API for reasons why) @param data a ByteArray containing the raw image data (assuming jpeg encoding, currently). *///from w ww .j a va 2s . com public static void putWikiImage(HttpClient httpclient, String filename, String description, HashMap<String, String> formfields, byte[] data) throws Exception { if (!formfields.containsKey("token")) { throw new WikiException(R.string.wiki_error_unknown); } HttpPost httppost = new HttpPost(WIKI_API_URL); // First, we need an edit token. Let's get one. ArrayList<NameValuePair> tnvps = new ArrayList<NameValuePair>(); tnvps.add(new BasicNameValuePair("action", "query")); tnvps.add(new BasicNameValuePair("prop", "info")); tnvps.add(new BasicNameValuePair("intoken", "edit")); tnvps.add(new BasicNameValuePair("titles", "UPLOAD_AN_IMAGE")); tnvps.add(new BasicNameValuePair("format", "xml")); httppost.setEntity(new UrlEncodedFormEntity(tnvps, "utf-8")); Document response = getHttpDocument(httpclient, httppost); Element root = response.getDocumentElement(); // Hopefully, a token exists. If not, a problem exists. String token; Element page; try { page = DOMUtil.getFirstElement(root, "page"); token = DOMUtil.getSimpleAttributeText(page, "edittoken"); } catch (Exception e) { throw new WikiException(R.string.wiki_error_xml); } // TOKEN GET! Now we've got us enough to get our upload on! Part[] nvps = new Part[] { new StringPart("action", "upload", "utf-8"), new StringPart("filename", filename, "utf-8"), new StringPart("comment", description, "utf-8"), new StringPart("watch", "true", "utf-8"), new StringPart("ignorewarnings", "true", "utf-8"), new StringPart("token", token, "utf-8"), new StringPart("format", "xml", "utf-8"), new FilePart("file", new ByteArrayPartSource(filename, data), "image/jpeg", "utf-8"), }; httppost.setEntity(new MultipartEntity(nvps, httppost.getParams())); response = getHttpDocument(httpclient, httppost); root = response.getDocumentElement(); // First, check for errors. if (doesResponseHaveError(root)) { throw new WikiException(getErrorTextId(findErrorCode(root))); } }