List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity()
From source file:net.zypr.api.Protocol.java
public JSONObject doStreamPost(APIVerbs apiVerb, Hashtable<String, String> urlParameters, Hashtable<String, String> postParameters, InputStream inputStream) throws APICommunicationException, APIProtocolException { if (!_apiEntity.equalsIgnoreCase("voice")) Session.getInstance().addActiveRequestCount(); long t1 = System.currentTimeMillis(); JSONObject jsonObject = null;/*from ww w . j a v a 2s. com*/ JSONParser jsonParser = new JSONParser(); try { DefaultHttpClient httpclient = getHTTPClient(); HttpPost httpPost = new HttpPost(buildURL(apiVerb, urlParameters)); HttpProtocolParams.setUseExpectContinue(httpPost.getParams(), false); MultipartEntity multipartEntity = new MultipartEntity(); if (postParameters != null) for (Enumeration enumeration = postParameters.keys(); enumeration.hasMoreElements();) { String key = enumeration.nextElement().toString(); String value = postParameters.get(key); multipartEntity.addPart(key, new StringBody(value)); Debug.print("HTTP POST : " + key + "=" + value); } if (inputStream != null) { InputStreamBody inputStreamBody = new InputStreamBody(inputStream, "binary/octet-stream"); multipartEntity.addPart("audio", inputStreamBody); } httpPost.setEntity(multipartEntity); HttpResponse httpResponse = httpclient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() != 200) throw new APICommunicationException("HTTP Error " + httpResponse.getStatusLine().getStatusCode() + " - " + httpResponse.getStatusLine().getReasonPhrase()); HttpEntity httpEntity = httpResponse.getEntity(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent())); jsonObject = (JSONObject) jsonParser.parse(bufferedReader); bufferedReader.close(); httpclient.getConnectionManager().shutdown(); } catch (ParseException parseException) { throw new APIProtocolException(parseException); } catch (IOException ioException) { throw new APICommunicationException(ioException); } catch (ClassCastException classCastException) { throw new APIProtocolException(classCastException); } finally { if (!_apiEntity.equalsIgnoreCase("voice")) Session.getInstance().removeActiveRequestCount(); long t2 = System.currentTimeMillis(); Debug.print(buildURL(apiVerb, urlParameters) + " : " + t1 + "-" + t2 + "=" + (t2 - t1) + " : " + jsonObject); } return (jsonObject); }
From source file:longism.com.api.APIUtils.java
/** * TODO Function:Upload file then Load json by type POST.<br> * * @param activity - to get context/*from w ww . j a va 2 s . com*/ * @param action - need authenticate or not, define at top of class * @param data - parameter String * @param files - param file input <key,path of file> * @param url - host of API * @param apiCallBack - call back to handle action when start, finish, success or fail * @date: July 07, 2015 * @author: Nguyen Long */ public static void loadJSONWithUploadFile(final Activity activity, final int action, final HashMap<String, String> data, final HashMap<String, String> files, final String url, final String sUserName, final String sUserPassword, final APICallBack apiCallBack) { activity.runOnUiThread(new Runnable() { @Override public void run() { apiCallBack.uiStart(); } }); new Thread(new Runnable() { @Override public synchronized void run() { try { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setSoTimeout(params, TIMEOUT_TIME); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_TIME); Charset chars = Charset.forName("UTF-8"); DefaultHttpClient client = new DefaultHttpClient(params); HttpPost post = new HttpPost(url); // DLog.e("Accountant", "url : " + url); MultipartEntity multipartEntity = new MultipartEntity(); if (files != null) { Set<String> set = files.keySet(); for (String key : set) { // DLog.e("Accountant", "param : " + key); File file = new File(files.get(key)); multipartEntity.addPart(key, new FileBody(file)); } } if (data != null) { Set<String> set = data.keySet(); for (String key : set) { // DLog.e("Accountant", "param : " + key); StringBody stringBody = new StringBody(data.get(key), chars); multipartEntity.addPart(key, stringBody); } } post.setEntity(multipartEntity); /** * if need authen then run this code below */ if (action == ACTION_UPLOAD_WITH_AUTH) { setAuthenticate(client, post, sUserName, sUserPassword); } HttpResponse response = null; response = client.execute(post); final StringBuilder builder = new StringBuilder(); if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { InputStream inputStream = response.getEntity().getContent(); Scanner scanner = new Scanner(inputStream); while (scanner.hasNext()) { builder.append(scanner.nextLine()); } inputStream.close(); scanner.close(); apiCallBack.success(builder.toString(), 0); } else { apiCallBack.fail(response != null && response.getStatusLine() != null ? "response null" : "" + response.getStatusLine().getStatusCode()); } } catch (final Exception e) { apiCallBack.fail(e.getMessage()); } finally { activity.runOnUiThread(new Runnable() { @Override public void run() { apiCallBack.uiEnd(); } }); } } }).start(); }
From source file:com.omt.syncpad.DemoKitActivity.java
private static void postFile() { try {// w w w .j ava 2 s .c om File f = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + fileName); mf.writeToFile(f); Log.i(TAG, "Midi file generated. Posting file"); HttpPost httppost = new HttpPost(url); MultipartEntity entity = new MultipartEntity(); entity.addPart("filename", new StringBody(fileName)); entity.addPart("fileext", new StringBody(extName)); entity.addPart("upfile", new FileBody(f)); HttpClient httpclient = new DefaultHttpClient(); httppost.setEntity(entity); httpclient.execute(httppost); //HttpResponse response = httpclient.execute(httppost); //Do something with response... Log.i(TAG, "File posted"); } catch (Exception e) { // show error e.printStackTrace(); return; } }
From source file:gov.nist.appvet.toolmgr.ToolServiceAdapter.java
public MultipartEntity getMultipartEntity() { final MultipartEntity entity = new MultipartEntity(); File apkFile = null;// www . java 2s. c o m FileBody fileBody = null; try { String fileUploadParamName = null; // Add parameter name-value pairs if (formParameterNames != null) { for (int i = 0; i < formParameterNames.size(); i++) { final String paramName = formParameterNames.get(i); String paramValue = formParameterValues.get(i); if (paramValue.equals("APP_FILE")) { fileUploadParamName = paramName; } else { if (paramValue.equals("APPVET_DEFINED")) { if (paramName.equals("appid")) { appInfo.log.debug("Found " + paramName + " = " + "'APPVET_DEFINED' for tool '" + id + "'. Setting to appid = '" + appInfo.appId + "'"); paramValue = appInfo.appId; } else { appInfo.log.error("Found " + paramName + " = " + "'APPVET_DEFINED' for tool '" + id + "' but no actual value is set by AppVet. Aborting."); return null; } } if ((paramName == null) || paramName.isEmpty()) { appInfo.log.warn("Param name is null or empty " + "for tool '" + name + "'"); } else if ((paramValue == null) || paramValue.isEmpty()) { appInfo.log.warn("Param value is null or empty " + "for tool '" + name + "'"); } StringBody partValue = new StringBody(paramValue, Charset.forName("UTF-8")); entity.addPart(paramName, partValue); partValue = null; } } } final String apkFilePath = appInfo.getIdPath() + "/" + appInfo.fileName; appInfo.log.debug("Sending file: " + apkFilePath); apkFile = new File(apkFilePath); fileBody = new FileBody(apkFile); entity.addPart(fileUploadParamName, fileBody); return entity; } catch (final UnsupportedEncodingException e) { appInfo.log.error(e.getMessage()); return null; } }
From source file:setiquest.renderer.Utils.java
/** * Send a random BSON file.// www. j a v a 2 s. c o m * @return the response from the web server. */ public static String sendRandomBsonFile() { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(getOfflineSubjectsURL()); String filename = getRandomFile(getBsonDataDir()); File f = new File(filename); if (!f.exists()) { Log.log("sendRandonBsonFile(): File \"" + filename + "\" does not exists."); return "sendRandonBsonFile(): File \"" + filename + "\" does not exists."; } //Parse info from the name. //Old file = act1207.1.5.bson = actId, pol, subchannel //New file name: act1207.1.0.5.bson = actid, pol, obsType, subchannel int actId = 0; int obsId = 0; int pol = 0; String subchannel = "0"; String shortName = f.getName(); String[] parts = shortName.split("\\."); if (parts.length == 4) //Old name type { actId = Integer.parseInt(parts[0].substring(3)); obsId = 0; //Default to this. pol = Integer.parseInt(parts[1]); subchannel = parts[2]; } else if (parts.length == 5) //New name type { actId = Integer.parseInt(parts[0].substring(3)); pol = Integer.parseInt(parts[1]); obsId = Integer.parseInt(parts[2]); subchannel = parts[3]; } else { Log.log("sendRandonBsonFile(): bad bson file name: " + shortName); return "sendRandonBsonFile(): bad bson file name: " + shortName; } Log.log("Sending " + filename + ", Act:" + actId + ", Obs type:" + obsId + ", Pol" + pol + ", subchannel:" + subchannel); FileBody bin = new FileBody(new File(filename)); try { StringBody comment = new StringBody("Filename: " + filename); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", bin); reqEntity.addPart("type", new StringBody("data/bson")); reqEntity.addPart("subject[activity_id]", new StringBody("" + actId)); reqEntity.addPart("subject[observation_id]", new StringBody("" + obsId)); reqEntity.addPart("subject[pol]", new StringBody("" + pol)); reqEntity.addPart("subject[subchannel]", new StringBody("" + subchannel)); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); //Log.log(response.toString()); String sendResult = "Sending: " + shortName + "\n"; sendResult += "subject[activity_id]: " + actId + "\n"; sendResult += "subject[observation_id]: " + obsId + "\n"; sendResult += "subject[pol]: " + pol + "\n"; sendResult += "subject[subchannel]: " + subchannel + "\n"; sendResult += response.toString() + "|\n"; return sendResult; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "undefined"; }
From source file:com.ibuildapp.romanblack.TableReservationPlugin.TableReservationEMailSignUpActivity.java
/** * Validate input data and signs up new user on iBuildApp. *///from ww w . j av a 2s .c o m private void registration() { if (signUpActive) { handler.sendEmptyMessage(SHOW_PROGRESS_DIALOG); new Thread(new Runnable() { public void run() { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpClient httpClient = new DefaultHttpClient(params); try { HttpPost httpPost = new HttpPost(TableReservationHTTP.SIGNUP_URL); String firstNameString = firstNameEditText.getText().toString(); String lastNameString = lastNameEditText.getText().toString(); String emailString = emailEditText.getText().toString(); String passwordString = passwordEditText.getText().toString(); String rePasswordString = rePasswordEditText.getText().toString(); MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("firstname", new StringBody(firstNameString, Charset.forName("UTF-8"))); multipartEntity.addPart("lastname", new StringBody(lastNameString, Charset.forName("UTF-8"))); multipartEntity.addPart("email", new StringBody(emailString, Charset.forName("UTF-8"))); multipartEntity.addPart("password", new StringBody(passwordString, Charset.forName("UTF-8"))); multipartEntity.addPart("password_confirm", new StringBody(rePasswordString, Charset.forName("UTF-8"))); // add security part multipartEntity.addPart("app_id", new StringBody(Statics.appId, Charset.forName("UTF-8"))); multipartEntity.addPart("token", new StringBody(Statics.appToken, Charset.forName("UTF-8"))); httpPost.setEntity(multipartEntity); String resp = httpClient.execute(httpPost, new BasicResponseHandler()); fwUser = JSONParser.parseLoginRequestString(resp); if (fwUser == null) { handler.sendEmptyMessage(EMEIL_IN_USE); handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG); return; } handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG); handler.sendEmptyMessage(CLOSE_ACTIVITY_OK); } catch (Exception e) { handler.sendEmptyMessage(CLOSE_ACTIVITY_BAD); } } }).start(); } else { if (firstNameEditText.getText().toString().length() == 0 || lastNameEditText.getText().toString().length() == 0 || emailEditText.getText().toString().length() == 0 || passwordEditText.getText().toString().length() == 0 || rePasswordEditText.getText().toString().length() == 0) { Toast.makeText(this, R.string.alert_registration_fillin_fields, Toast.LENGTH_LONG).show(); return; } if (firstNameEditText.getText().toString().equals(lastNameEditText.getText().toString())) { Toast.makeText(this, R.string.alert_registration_spam, Toast.LENGTH_LONG).show(); return; } if (firstNameEditText.getText().toString().length() <= 2 || lastNameEditText.getText().toString().length() <= 2) { Toast.makeText(this, R.string.alert_registration_two_symbols_name, Toast.LENGTH_LONG).show(); return; } String regExpn = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@" + "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?" + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\." + "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?" + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" + "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$"; Pattern pattern = Pattern.compile(regExpn, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(emailEditText.getText().toString()); if (matcher.matches()) { } else { Toast.makeText(this, R.string.alert_registration_correct_email, Toast.LENGTH_LONG).show(); return; } if (passwordEditText.getText().toString().length() < 4) { Toast.makeText(this, R.string.alert_registration_two_symbols_password, Toast.LENGTH_LONG).show(); return; } if (!passwordEditText.getText().toString().equals(rePasswordEditText.getText().toString())) { Toast.makeText(this, "Passwords don't match.", Toast.LENGTH_LONG).show(); return; } } }
From source file:eu.geopaparazzi.library.network.NetworkUtilities.java
/** * Sends a {@link MultipartEntity} post with text and image files. * /* w w w . j a v a 2s . co m*/ * @param url the url to which to POST to. * @param user the user or <code>null</code>. * @param pwd the password or <code>null</code>. * @param stringsMap the {@link HashMap} containing the key and string pairs to send. * @param filesMap the {@link HashMap} containing the key and image file paths * (jpg, png supported) pairs to send. * @throws UnsupportedEncodingException * @throws IOException * @throws ClientProtocolException */ public static void sentMultiPartPost(String url, String user, String pwd, HashMap<String, String> stringsMap, HashMap<String, File> filesMap) throws UnsupportedEncodingException, IOException, ClientProtocolException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost(url); if (user != null && pwd != null) { String ret = getB64Auth(user, pwd); httppost.setHeader("Authorization", ret); } MultipartEntity mpEntity = new MultipartEntity(); Set<Entry<String, String>> stringsEntrySet = stringsMap.entrySet(); for (Entry<String, String> stringEntry : stringsEntrySet) { ContentBody cbProperties = new StringBody(stringEntry.getValue()); mpEntity.addPart(stringEntry.getKey(), cbProperties); } Set<Entry<String, File>> filesEntrySet = filesMap.entrySet(); for (Entry<String, File> filesEntry : filesEntrySet) { String propName = filesEntry.getKey(); File file = filesEntry.getValue(); if (file.exists()) { String ext = file.getName().toLowerCase().endsWith("jpg") ? "jpeg" : "png"; ContentBody cbFile = new FileBody(file, "image/" + ext); mpEntity.addPart(propName, cbFile); } } httppost.setEntity(mpEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { resEntity.consumeContent(); } httpclient.getConnectionManager().shutdown(); }
From source file:org.rapidandroid.activity.FormReviewer.java
private void uploadFile(final String filename) { Toast.makeText(getApplicationContext(), FILE_UPLOAD_BEGUN, Toast.LENGTH_LONG).show(); Thread t = new Thread() { @Override/*from w w w . j a v a 2 s .co m*/ public void run() { try { DefaultHttpClient httpclient = new DefaultHttpClient(); File f = new File(filename); HttpPost httpost = new HttpPost("http://192.168.7.127:8160/upload/upload"); MultipartEntity entity = new MultipartEntity(); entity.addPart("myIdentifier", new StringBody("somevalue")); entity.addPart("myFile", new FileBody(f)); httpost.setEntity(entity); HttpResponse response; // Post, check and show the result (not really spectacular, // but works): response = httpclient.execute(httpost); Log.d("httpPost", "Login form get: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } success = true; } catch (Exception ex) { Log.d("FormReviewer", "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace()); success = false; } finally { mDebugHandler.post(mFinishUpload); } } }; t.start(); }
From source file:ca.sqlpower.enterprise.ClientSideSessionUtils.java
public static ProjectLocation uploadProject(SPServerInfo serviceInfo, String name, File project, UserPrompterFactory session, CookieStore cookieStore) throws URISyntaxException, ClientProtocolException, IOException, JSONException { HttpClient httpClient = ClientSideSessionUtils.createHttpClient(serviceInfo, cookieStore); try {/*from w w w . j ava 2 s . c o m*/ MultipartEntity entity = new MultipartEntity(); ContentBody fileBody = new FileBody(project); ContentBody nameBody = new StringBody(name); entity.addPart("file", fileBody); entity.addPart("name", nameBody); HttpPost request = new HttpPost(ClientSideSessionUtils.getServerURI(serviceInfo, "/" + ClientSideSessionUtils.REST_TAG + "/jcr", "name=" + name)); request.setEntity(entity); JSONMessage message = httpClient.execute(request, new JSONResponseHandler()); JSONObject response = new JSONObject(message.getBody()); return new ProjectLocation(response.getString("uuid"), response.getString("name"), serviceInfo); } catch (AccessDeniedException e) { session.createUserPrompter("You do not have sufficient privileges to create a new workspace.", UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK").promptUser(""); return null; } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:uk.co.tfd.sm.proxy.ProxyClientServiceImpl.java
/** * Executes a HTTP call using a path in the JCR to point to a template and a * map of properties to populate that template with. An example might be a * SOAP call.//from w ww .j a va2 s . c o m * * <pre> * {http://www.w3.org/2001/12/soap-envelope}Envelope:{ * {http://www.w3.org/2001/12/soap-envelope}Body:{ * {http://www.example.org/stock}GetStockPriceResponse:{ * >body:[ ] * {http://www.example.org/stock}Price:{ * >body:[34.5] * } * } * >body:[ ] * } * >body:[ ] * {http://www.w3.org/2001/12/soap-envelope}encodingStyle:[http://www.w3.org/2001/12/soap-encoding] * } * * </pre> * * @param resource * the resource containing the proxy end point specification. * @param headers * a map of headers to set int the request. * @param input * a map of parameters for all templates (both url and body) * @param requestInputStream * containing the request body (can be null if the call requires * no body or the template will be used to generate the body) * @param requestContentLength * if the requestImputStream is specified, the length specifies * the lenght of the body. * @param requerstContentType * the content type of the request, if null the node property * sakai:proxy-request-content-type will be used. * @throws ProxyClientException */ public ProxyResponse executeCall(Map<String, Object> config, Map<String, Object> headers, Map<String, Object> input, InputStream requestInputStream, long requestContentLength, String requestContentType) throws ProxyClientException { try { LOGGER.info( "Calling Execute Call with Config:[{}] Headers:[{}] Input:[{}] " + "RequestInputStream:[{}] InputStreamContentLength:[{}] RequestContentType:[{}] ", new Object[] { config, headers, input, requestInputStream, requestContentLength, requestContentType }); bindConfig(config); if (config != null && config.containsKey(CONFIG_REQUEST_PROXY_ENDPOINT)) { // setup the post request String endpointURL = (String) config.get(CONFIG_REQUEST_PROXY_ENDPOINT); if (isUnsafeProxyDefinition(config)) { try { URL u = new URL(endpointURL); String host = u.getHost(); if (host.indexOf('$') >= 0) { throw new ProxyClientException( "Invalid Endpoint template, relies on request to resolve valid URL " + u); } } catch (MalformedURLException e) { throw new ProxyClientException( "Invalid Endpoint template, relies on request to resolve valid URL", e); } } LOGGER.info("Valied Endpoint Def"); Map<String, Object> context = Maps.newHashMap(input); // add in the config properties from the bundle overwriting // everything else. context.put("config", configProperties); endpointURL = processUrlTemplate(endpointURL, context); LOGGER.info("Calling URL {} ", endpointURL); ProxyMethod proxyMethod = ProxyMethod.GET; if (config.containsKey(CONFIG_REQUEST_PROXY_METHOD)) { try { proxyMethod = ProxyMethod.valueOf((String) config.get(CONFIG_REQUEST_PROXY_METHOD)); } catch (Exception e) { } } HttpClient client = getHttpClient(); HttpUriRequest method = null; switch (proxyMethod) { case GET: if (config.containsKey(CONFIG_LIMIT_GET_SIZE)) { long maxSize = (Long) config.get(CONFIG_LIMIT_GET_SIZE); HttpHead h = new HttpHead(endpointURL); HttpParams params = h.getParams(); // make certain we reject the body of a head params.setBooleanParameter("http.protocol.reject-head-body", true); h.setParams(params); populateMessage(method, config, headers); HttpResponse response = client.execute(h); if (response.getStatusLine().getStatusCode() == 200) { // Check if the content-length is smaller than the // maximum (if any). Header contentLengthHeader = response.getLastHeader("Content-Length"); if (contentLengthHeader != null) { long length = Long.parseLong(contentLengthHeader.getValue()); if (length > maxSize) { return new ProxyResponseImpl(HttpServletResponse.SC_PRECONDITION_FAILED, "Response too large", response); } } } else { return new ProxyResponseImpl(response); } } method = new HttpGet(endpointURL); break; case HEAD: method = new HttpHead(endpointURL); break; case OPTIONS: method = new HttpOptions(endpointURL); break; case POST: method = new HttpPost(endpointURL); break; case PUT: method = new HttpPut(endpointURL); break; default: method = new HttpGet(endpointURL); } populateMessage(method, config, headers); if (requestInputStream == null && !config.containsKey(CONFIG_PROXY_REQUEST_TEMPLATE)) { if (method instanceof HttpPost) { HttpPost postMethod = (HttpPost) method; MultipartEntity multipart = new MultipartEntity(); for (Entry<String, Object> param : input.entrySet()) { String key = param.getKey(); Object value = param.getValue(); if (value instanceof Object[]) { for (Object val : (Object[]) value) { addPart(multipart, key, val); } } else { addPart(multipart, key, value); } postMethod.setEntity(multipart); } } } else { if (method instanceof HttpEntityEnclosingRequestBase) { String contentType = requestContentType; if (contentType == null && config.containsKey(CONFIG_REQUEST_CONTENT_TYPE)) { contentType = (String) config.get(CONFIG_REQUEST_CONTENT_TYPE); } if (contentType == null) { contentType = APPLICATION_OCTET_STREAM; } HttpEntityEnclosingRequestBase eemethod = (HttpEntityEnclosingRequestBase) method; if (requestInputStream != null) { eemethod.setHeader(HttpHeaders.CONTENT_TYPE, contentType); eemethod.setEntity(new InputStreamEntity(requestInputStream, requestContentLength)); } else { // build the request StringWriter body = new StringWriter(); templateService.evaluate(context, body, (String) config.get("path"), (String) config.get(CONFIG_PROXY_REQUEST_TEMPLATE)); byte[] soapBodyContent = body.toString().getBytes("UTF-8"); eemethod.setHeader(HttpHeaders.CONTENT_TYPE, contentType); eemethod.setEntity(new InputStreamEntity(new ByteArrayInputStream(soapBodyContent), soapBodyContent.length)); } } } HttpResponse response = client.execute(method); if (response.getStatusLine().getStatusCode() == 302 && method instanceof HttpEntityEnclosingRequestBase) { // handle redirects on post and put String url = response.getFirstHeader("Location").getValue(); method = new HttpGet(url); response = client.execute(method); } return new ProxyResponseImpl(response); } } catch (ProxyClientException e) { throw e; } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw new ProxyClientException("The Proxy request specified by " + config + " failed, cause follows:", e); } finally { unbindConfig(); } throw new ProxyClientException( "The Proxy request specified by " + config + " does not contain a valid endpoint specification "); }