List of usage examples for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity
public StringRequestEntity(String paramString1, String paramString2, String paramString3) throws UnsupportedEncodingException
From source file:com.honnix.yaacs.adapter.http.TestACHttpServer.java
public void testGetACList() { Map<String, String> paramMap = null; String sessionId = null;//from w ww . j a v a 2 s .c om try { paramMap = login(); sessionId = paramMap.get(ACHttpConstant.SESSION_ID_KEY); assertNotNull(RESPONSE_ERROR, sessionId); } catch (HttpException e) { fail(FORCED_FAILURE); } catch (IOException e) { fail(FORCED_FAILURE); } StringBuilder sb = new StringBuilder(HOST).append(ACHttpPropertiesConstant.HTTP_LISTENING_PORT) .append(ACHttpPropertiesConstant.HTTP_AC_REQUEST_URL); postMethod = new PostMethod(sb.toString()); postMethod.setRequestHeader(CONTENT_TYPE_KEY, CONTENT_TYPE); try { StringRequestEntity requestEntity = new StringRequestEntity( ACHttpBodyUtil.buildGetACListByAlbumRequestBody(sessionId, "Honnix", "2008", "Shadow of Light"), null, ACHttpPropertiesConstant.HTTP_CHARSET); postMethod.setRequestEntity(requestEntity); int statusCode = client.executeMethod(postMethod); assertEquals(SHOULD_BE_OK, HttpStatus.SC_OK, statusCode); String response = postMethod.getResponseBodyAsString(); assertTrue(RESPONSE_ERROR, response.startsWith(SUCCESS_RESP)); byte[] byteArray = new byte[3]; byteArray[0] = 97; byteArray[1] = 98; byteArray[2] = 99; assertNotSame(RESPONSE_ERROR, -1, response.indexOf(StringUtil.encodeBase64(byteArray))); } catch (HttpException e) { fail(FORCED_FAILURE); } catch (IOException e) { fail(FORCED_FAILURE); } try { StringRequestEntity requestEntity = new StringRequestEntity( ACHttpBodyUtil.buildGetACListByDiscIdRequestBody(sessionId, "aac6400f48249cc9763771cc626a3571"), null, ACHttpPropertiesConstant.HTTP_CHARSET); postMethod = new PostMethod(sb.toString()); postMethod.setRequestHeader(CONTENT_TYPE_KEY, CONTENT_TYPE); postMethod.setRequestEntity(requestEntity); int statusCode = client.executeMethod(postMethod); assertEquals(SHOULD_BE_OK, HttpStatus.SC_OK, statusCode); String response = postMethod.getResponseBodyAsString(); assertTrue(RESPONSE_ERROR, response.startsWith(SUCCESS_RESP)); byte[] byteArray = new byte[3]; byteArray[0] = 97; byteArray[1] = 98; byteArray[2] = 99; assertNotSame(RESPONSE_ERROR, -1, response.indexOf(StringUtil.encodeBase64(byteArray))); } catch (HttpException e) { fail(FORCED_FAILURE); } catch (IOException e) { fail(FORCED_FAILURE); } }
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 ww . j av a 2 s .co 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:com.bigdata.rdf.sail.remoting.GraphRepositoryClient.java
/** * @see {@link GraphRepository#create(String)} *//* w w w .ja v a 2 s . co m*/ public void create(String rdfXml) throws Exception { // POST PostMethod post = new PostMethod(servletURL); try { // set the body if (rdfXml != null) { post.setRequestEntity(new StringRequestEntity(rdfXml, // the rdf/xml body GraphRepositoryServlet.RDF_XML, // includes the encoding null // so we don't need to say it here. )); post.setContentChunked(true); } // Execute the method. int sc = getHttpClient().executeMethod(post); if (sc != HttpStatus.SC_OK) { throw new IOException("HTTP-POST failed: " + post.getStatusLine()); } } finally { // Release the connection. post.releaseConnection(); } }
From source file:gr.upatras.ece.nam.fci.uop.UoPGWClient.java
/** * It makes a POST towards the gateway// w ww . ja v a2 s. co m * @author ctranoris * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27 * @param ptmAlias sets the name of the provider URI, e.g.: uop * @param content sets the name of the content; send in utf8 */ public boolean POSTExecute(String resourceInstance, String ptmAlias, String content) { boolean status = false; log.info("content body=" + "\n" + content); HttpClient client = new HttpClient(); String tgwcontent = content; // resource instance is like uop.rubis_db-6 so we need to make it like // this /uop/uop.rubis_db-6 String ptm = ptmAlias; String url = uopGWAddress + "/" + ptm + "/" + resourceInstance; log.info("Request: " + url); // Create a method instance. PostMethod post = new PostMethod(url); post.setRequestHeader("User-Agent", userAgent); post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Provide custom retry handler is necessary post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); //HttpMethodParams. RequestEntity requestEntity = null; try { requestEntity = new StringRequestEntity(tgwcontent, "application/x-www-form-urlencoded", "utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } post.setRequestEntity(requestEntity); try { // Execute the method. int statusCode = client.executeMethod(post); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + post.getStatusLine()); } // Deal with the response. // Use caution: ensure correct character encoding and is not binary // data // print the status and response InputStream responseBody = post.getResponseBodyAsStream(); CopyInputStream cis = new CopyInputStream(responseBody); response_stream = cis.getCopy(); log.info("Response body=" + "\n" + convertStreamToString(response_stream)); response_stream.reset(); // log.info("for address: " + url + " the response is:\n " // + post.getResponseBodyAsString()); status = true; } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); return false; } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); return false; } finally { // Release the connection. post.releaseConnection(); } return status; }
From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java
@Override public AuthenticationResponse authenticate(Long operatorId, String username, String password) { PostMethod method = new PostMethod(baseUrl + AUTHENTICATE); AuthenticationRequest request = new AuthenticationRequest(); request.setOperatorId(operatorId);//from w ww . j ava 2s .co m request.setUserName(username); request.setPassword(password); try { String data = serialize(request); method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8")); // Execute the HTTP Call int statusCode = getClient().executeMethod(method); if (statusCode == HttpStatus.SC_NOT_FOUND) { return null; } if (statusCode == HttpStatus.SC_UNAUTHORIZED) { AuthenticationResponse response = new AuthenticationResponse(); response.setAuthenticated(false); return response; } else if (statusCode == HttpStatus.SC_OK) { InputStream body = method.getResponseBodyAsStream(); return parseJson(body, AuthenticationResponse.class); } else { throw new RuntimeException("Failed to authenticate user, RESPONSE CODE: " + statusCode); } } catch (Exception e) { throw new RuntimeException(e); } finally { method.releaseConnection(); } }
From source file:com.rometools.propono.atom.client.ClientEntry.java
/** * Update entry by posting new representation of entry to server. Note that you should not * attempt to update entries that you get from iterating over a collection they may be "partial" * entries. If you want to update an entry, you must get it via one of the * <code>getEntry()</code> methods in {@link com.rometools.rome.propono.atom.common.Collection} * or {@link com.rometools.rome.propono.atom.common.AtomService}. * * @throws ProponoException If entry is a "partial" entry. *///w ww . j a v a 2s.c o m public void update() throws ProponoException { if (partial) { throw new ProponoException("ERROR: attempt to update partial entry"); } final EntityEnclosingMethod method = new PutMethod(getEditURI()); addAuthentication(method); final StringWriter sw = new StringWriter(); final int code = -1; try { Atom10Generator.serializeEntry(this, sw); method.setRequestEntity(new StringRequestEntity(sw.toString(), null, null)); method.setRequestHeader("Content-type", "application/atom+xml; charset=utf-8"); getHttpClient().executeMethod(method); final InputStream is = method.getResponseBodyAsStream(); if (method.getStatusCode() != 200 && method.getStatusCode() != 201) { throw new ProponoException( "ERROR HTTP status=" + method.getStatusCode() + " : " + Utilities.streamToString(is)); } } catch (final Exception e) { final String msg = "ERROR: updating entry, HTTP code: " + code; LOG.debug(msg, e); throw new ProponoException(msg, e); } finally { method.releaseConnection(); } }
From source file:gr.upatras.ece.nam.fci.panlab.PanlabGWClient.java
/** * It makes a POST towards the gateway/*from w ww. j a va 2 s . com*/ * @author ctranoris * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27 * @param ptmAlias sets the name of the provider URI, e.g.: uop * @param content sets the name of the content; send in utf8 */ public boolean POSTExecute(String resourceInstance, String ptmAlias, String content) { boolean status = false; System.out.println("content body=" + "\n" + content); HttpClient client = new HttpClient(); String tgwcontent = content; // resource instance is like uop.rubis_db-6 so we need to make it like // this /uop/uop.rubis_db-6 String ptm = ptmAlias; String url = panlabGWAddress + "/" + ptm + "/" + resourceInstance; System.out.println("Request: " + url); // Create a method instance. PostMethod post = new PostMethod(url); post.setRequestHeader("User-Agent", userAgent); post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Provide custom retry handler is necessary post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); //HttpMethodParams. RequestEntity requestEntity = null; try { requestEntity = new StringRequestEntity(tgwcontent, "application/x-www-form-urlencoded", "utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } post.setRequestEntity(requestEntity); try { // Execute the method. int statusCode = client.executeMethod(post); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + post.getStatusLine()); } // Deal with the response. // Use caution: ensure correct character encoding and is not binary // data // print the status and response InputStream responseBody = post.getResponseBodyAsStream(); CopyInputStream cis = new CopyInputStream(responseBody); response_stream = cis.getCopy(); System.out.println("Response body=" + "\n" + convertStreamToString(response_stream)); response_stream.reset(); // System.out.println("for address: " + url + " the response is:\n " // + post.getResponseBodyAsString()); status = true; } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); return false; } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); return false; } finally { // Release the connection. post.releaseConnection(); } return status; }
From source file:it.geosolutions.geoserver.rest.HTTPUtils.java
/** * PUTs a String to the given URL. <BR> * Basic auth is used if both username and pw are not null. * //from www. j a v a 2 s. c o m * @param url The URL where to connect to. * @param content The content to be sent as a String. * @param contentType The content-type to advert in the PUT. * @param username Basic auth credential. No basic auth if null. * @param pw Basic auth credential. No basic auth if null. * @return The HTTP response as a String if the HTTP response code was 200 * (OK). * @throws MalformedURLException * @return the HTTP response or <TT>null</TT> on errors. */ public static String put(String url, String content, String contentType, String username, String pw) { try { return put(url, new StringRequestEntity(content, contentType, null), username, pw); } catch (UnsupportedEncodingException ex) { LOGGER.error("Cannot PUT " + url, ex); return null; } }
From source file:net.jadler.AbstractJadlerStubbingIntegrationTest.java
@Test public void havingEmptyBody() throws Exception { onRequest().havingBodyEqualTo("").havingBody(notNullValue()).havingBody(isEmptyString()).respond() .withStatus(201);//from w w w . ja v a 2 s . c o m final PostMethod method = new PostMethod("http://localhost:" + port()); method.setRequestEntity(new StringRequestEntity("", null, null)); int status = client.executeMethod(method); assertThat(status, is(201)); method.releaseConnection(); }
From source file:com.tops.hotelmanager.util.CommonHttpClient.java
private static String executePOSTRequestV1(String url, Map<String, Object> requestData, Map<String, String> headerMap, String contentType, int timeOut, int retry) { PostMethod post = new PostMethod(url); Gson gson = new Gson(); String errorMsg = "error~Request Failed"; try {//from w w w . jav a 2s .c o m HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setSoTimeout(timeOut); client.getHttpConnectionManager().getParams().setConnectionTimeout(timeOut); if (requestData == null || requestData.isEmpty()) { throw new CustomException("Request data is null"); } if (contentType != null && contentType.equals(CommonHttpClient.CONTENT_TYPE_JSON)) { StringRequestEntity requestEntity = new StringRequestEntity(gson.toJson(requestData), contentType, "UTF-8"); post.setRequestEntity(requestEntity); } else { // SET REQUEST PARAMETER for (Map.Entry<String, Object> entry : requestData.entrySet()) { post.addParameter(entry.getKey(), String.valueOf(entry.getValue())); } } // SET REQUEST HEADER if (headerMap != null) { for (Map.Entry<String, String> entry : headerMap.entrySet()) { post.addRequestHeader(entry.getKey(), entry.getValue()); } } int status = client.executeMethod(post); // System.out.println("URL:" + url); // System.out.println("\n REQUEST HEADERS:"); // Header[] requestHeaders = post.getRequestHeaders(); // for (Header header : requestHeaders) { // System.out.println(header.getName() + "=" + header.getValue()); // } // System.out.println("\n RESPONSE HEADERS:"); // Header[] responseHeaders = post.getResponseHeaders(); // for (Header header : responseHeaders) { // System.out.println(header.getName() + "=" + header.getValue()); // } // System.out.println(post.getStatusText()); // System.out.println(post.getStatusLine().getReasonPhrase()); // System.out.println(post.getResponseBodyAsString()); if (status == HttpStatus.SC_OK) { return post.getResponseBodyAsString(); } else if (status == HttpStatus.SC_TEMPORARY_REDIRECT) { Header header = post.getResponseHeader("Location"); if (retry != 1) { errorMsg = executePOSTRequestV1(header.getValue(), requestData, headerMap, contentType, timeOut, retry++); } } else { errorMsg += ",HttpStatus:" + status; } } catch (Exception ex) { logger.error("executePOSTRequestV1 url: " + url + ", Parameters: " + requestData, ex); errorMsg = errorMsg + ":" + ex.getMessage(); } finally { post.releaseConnection(); } return errorMsg; }