Java Code Examples for org.apache.commons.httpclient.methods.PostMethod#setRequestHeader()

The following examples show how to use org.apache.commons.httpclient.methods.PostMethod#setRequestHeader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Simulator.java    From realtime-analytics with GNU General Public License v2.0 6 votes vote down vote up
private void init() {
	initList(m_ipList, ipFilePath);
	initList(m_uaList, uaFilePath);
	initList(m_itemList, itmFilePath);
	initList(m_tsList,tsFilePath);
	initList(m_siteList,siteFilePath);
	initList(m_dsList,dsFilePath);
	initGUIDList();

	String finalURL = "";
	if (batchMode) {
		finalURL = BATCH_URL;
	} else {
		finalURL = URL;
	}
	m_payload = readFromResource();
	HttpClientParams clientParams = new HttpClientParams();
	clientParams.setSoTimeout(60000);
	m_client = new HttpClient(clientParams);
	m_method = new PostMethod(NODE + finalURL + EVENTTYPE);
	m_method.setRequestHeader("Connection", "Keep-Alive");
	m_method.setRequestHeader("Accept-Charset", "UTF-8");
}
 
Example 2
Source File: JunkUtils.java    From http4e with Apache License 2.0 6 votes vote down vote up
public static String getHdToken(String url, String md){
      final HttpClient client = new HttpClient();      
      PostMethod post = new PostMethod(url);
      post.setRequestHeader("content-type", "application/x-www-form-urlencoded");
      post.setParameter("v", md);
      
      post.setApacheHttpListener(httpListener);
      try {
         HttpUtils.execute(client, post, responseReader);
         Header header = post.getResponseHeader("hd-token");
         if(header != null){
//            System.out.println("hd-token:" + header.getValue() + "'");
            return header.getValue();
         }
      } catch (Exception ignore) {
         ExceptionHandler.handle(ignore);
      } finally {
         if(post != null) post.releaseConnection();
      }
      return null;
   }
 
Example 3
Source File: ReplaceJSONPayloadTestcase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
private String httpClient(String proxyLocation, String xml) {
    try {
        HttpClient httpclient = new HttpClient();
        PostMethod post = new PostMethod(proxyLocation);

        post.setRequestEntity(new StringRequestEntity(xml));
        post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
        post.setRequestHeader("SOAPAction", "urn:mediate");
        httpclient.executeMethod(post);

        InputStream in = post.getResponseBodyAsStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        StringBuffer buffer = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
            buffer.append("\n");
        }
        reader.close();
        return buffer.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: ESBJAVA4846HttpProtocolVersionTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Sending HTTP1.0 message")
public void sendingHTTP10Message() throws Exception {
    PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion"));
    RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "urn:getQuote");
    HttpMethodParams params = new HttpMethodParams();
    params.setVersion(HttpVersion.HTTP_1_0);
    post.setParams(params);
    HttpClient httpClient = new HttpClient();
    String httpVersion = "";

    try {
        httpClient.executeMethod(post);
        post.getResponseBodyAsString();
        httpVersion = post.getStatusLine().getHttpVersion();
    } finally {
        post.releaseConnection();
    }
    Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_0.toString(), "Http version mismatched");

}
 
Example 5
Source File: TelegramMessage.java    From build-notifications-plugin with MIT License 6 votes vote down vote up
public void send() {
  String[] ids = chatIds.split("\\s*,\\s*");
  HttpClient client = new HttpClient();
  for (String chatId : ids) {
    PostMethod post = new PostMethod(String.format(
        "https://api.telegram.org/bot%s/sendMessage",
        botToken
    ));

    post.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");

    post.setRequestBody(new NameValuePair[]{
        new NameValuePair("chat_id", chatId),
        new NameValuePair("text", getMessage())
    });
    try {
      client.executeMethod(post);
    } catch (IOException e) {
      LOGGER.severe("Error while sending notification: " + e.getMessage());
      e.printStackTrace();
    }
  }
}
 
Example 6
Source File: ESBJAVA2615TestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private String httpClient(String proxyLocation, String xml) {
    try {
        HttpClient httpclient = new HttpClient();
        PostMethod post = new PostMethod(proxyLocation);

        post.setRequestEntity(new StringRequestEntity(xml));
        post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
        post.setRequestHeader("SOAPAction", "urn:mediate");
        httpclient.executeMethod(post);

        InputStream in = post.getResponseBodyAsStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        StringBuffer buffer = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
            buffer.append("\n");
        }
        reader.close();
        return buffer.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 7
Source File: ESBJAVA2615TestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
private String httpClient(String proxyLocation, String xml) {
    try {
        HttpClient httpclient = new HttpClient();
        PostMethod post = new PostMethod(proxyLocation);

        post.setRequestEntity(new StringRequestEntity(xml));
        post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
        post.setRequestHeader("SOAPAction", "urn:mediate");
        httpclient.executeMethod(post);

        InputStream in = post.getResponseBodyAsStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        StringBuffer buffer = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
            buffer.append("\n");
        }
        reader.close();
        return buffer.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: ESBJAVA4846HttpProtocolVersionTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Sending HTTP1.1 message")
public void sendingHTTP11Message() throws Exception {
    PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion"));
    RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "urn:getQuote");
    HttpMethodParams params = new HttpMethodParams();
    params.setVersion(HttpVersion.HTTP_1_1);
    post.setParams(params);
    HttpClient httpClient = new HttpClient();
    String httpVersion = "";

    try {
        httpClient.executeMethod(post);
        post.getResponseBodyAsString();
        httpVersion = post.getStatusLine().getHttpVersion();
    } finally {
        post.releaseConnection();
    }
    Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_1.toString(), "Http version mismatched");
}
 
Example 9
Source File: UcsHttpClient.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public String call(String xml) {
    PostMethod post = new PostMethod(url);
    post.setRequestEntity(new StringRequestEntity(xml));
    post.setRequestHeader("Content-type", "text/xml");
    //post.setFollowRedirects(true);
    try {
        int result = client.executeMethod(post);
        if (result == 302) {
            // Handle HTTPS redirect
            // Ideal way might be to configure from add manager API
            // for using either HTTP / HTTPS
            // Allow only one level of redirect
            String redirectLocation;
            Header locationHeader = post.getResponseHeader("location");
            if (locationHeader != null) {
                redirectLocation = locationHeader.getValue();
            } else {
                throw new CloudRuntimeException("Call failed: Bad redirect from UCS Manager");
            }
            post.setURI(new URI(redirectLocation));
            result = client.executeMethod(post);
        }
        // Check for errors
        if (result != 200) {
            throw new CloudRuntimeException("Call failed: " + post.getResponseBodyAsString());
        }
        String res = post.getResponseBodyAsString();
        if (res.contains("errorCode")) {
            String err = String.format("ucs call failed:\nsubmitted doc:%s\nresponse:%s\n", xml, res);
            throw new CloudRuntimeException(err);
        }
        return res;
    } catch (Exception e) {
        throw new CloudRuntimeException(e.getMessage(), e);
    } finally {
        post.releaseConnection();
    }
}
 
Example 10
Source File: PropertyIntegrationForceSCAcceptedPropertyTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Test(groups = "wso2.esb", description = "Testing functionality of FORCE_SC_ACCEPTED " +
                                         "Enabled True  - " +
                                         "Client should receive 202 message",
      dependsOnMethods = "testFORCE_SC_ACCEPTEDPropertyEnabledFalseScenario")
public void testWithFORCE_SC_ACCEPTEDPropertyEnabledTrueScenario() throws Exception {
    verifyProxyServiceExistence("FORCE_SC_ACCEPTED_TrueTestProxy");

    int responseStatus = 0;

    String strXMLFilename = FrameworkPathUtil.getSystemResourceLocation() + "artifacts"
                            + File.separator + "ESB" + File.separator + "mediatorconfig" +
                            File.separator + "property" + File.separator + "PlaceOrder.xml";

    File input = new File(strXMLFilename);
    PostMethod post = new PostMethod(getProxyServiceURLHttp("FORCE_SC_ACCEPTED_TrueTestProxy"));
    RequestEntity entity = new FileRequestEntity(input, "text/xml");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "placeOrder");

    HttpClient httpclient = new HttpClient();

    try {
        responseStatus = httpclient.executeMethod(post);
    } finally {
        post.releaseConnection();
    }

    assertEquals(responseStatus, 202, "Response status should be 202");
}
 
Example 11
Source File: DifidoClient.java    From difido-reports with Apache License 2.0 5 votes vote down vote up
public int addMachine(int executionId, MachineNode machine) throws Exception {
	PostMethod method = new PostMethod(baseUri + "executions/" + executionId + "/machines/");
	method.setRequestHeader(new Header("Content-Type", "application/json"));
	final ObjectMapper mapper = new ObjectMapper();
	final String json = mapper.writeValueAsString(machine);
	final RequestEntity entity = new StringRequestEntity(json,"application/json","UTF-8");
	method.setRequestEntity(entity);
	int responseCode = client.executeMethod(method);
	handleResponseCode(method, responseCode);
	return Integer.parseInt(method.getResponseBodyAsString());
}
 
Example 12
Source File: DifidoClient.java    From difido-reports with Apache License 2.0 5 votes vote down vote up
public void addTestDetails(int executionId, TestDetails testDetails) throws Exception {
	PostMethod method = new PostMethod(baseUri + "executions/" + executionId + "/details");
	method.setRequestHeader(new Header("Content-Type", "application/json"));
	final ObjectMapper mapper = new ObjectMapper();
	final String json = mapper.writeValueAsString(testDetails);
	final RequestEntity entity = new StringRequestEntity(json,"application/json","UTF-8");
	method.setRequestEntity(entity);
	final int responseCode = client.executeMethod(method);
	handleResponseCode(method, responseCode);
}
 
Example 13
Source File: ESBJAVA_4239_HTTP_SC_HandlingTests.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@Test(groups = "wso2.esb", description = "Test whether response HTTP status code getting correctly after callout "
        + "mediator successfully execute")
public void testHttpStatusCodeGettingSuccessfully() throws Exception {
    String endpoint = getProxyServiceURLHttp("TestCalloutHTTP_SC");
    String soapRequest =
            TestConfigurationProvider.getResourceLocation() + "artifacts" + File.separator + "ESB" + File.separator
                    + "mediatorconfig" + File.separator + "callout" + File.separator + "SOAPRequestWithHeader.xml";
    File input = new File(soapRequest);
    PostMethod post = new PostMethod(endpoint);
    RequestEntity entity = new FileRequestEntity(input, "text/xml");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "getQuote");
    HttpClient httpClient = new HttpClient();
    boolean errorLog = false;

    try {
        httpClient.executeMethod(post);
        errorLog = carbonLogReader.checkForLog("STATUS-Fault", DEFAULT_TIMEOUT) && carbonLogReader.
                checkForLog("404 Error: Not Found", DEFAULT_TIMEOUT);
        carbonLogReader.stop();
    } finally {
        post.releaseConnection();
    }

    if (!errorLog) {
        fail("Response HTTP code not return successfully.");
    }
}
 
Example 14
Source File: ZeppelinServerMock.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
protected static PostMethod httpPost(String path, String request, String user, String pwd)
    throws IOException {
  LOG.info("Connecting to {}", URL + path);
  HttpClient httpClient = new HttpClient();
  PostMethod postMethod = new PostMethod(URL + path);
  postMethod.setRequestBody(request);
  postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
  if (userAndPasswordAreNotBlank(user, pwd)) {
    postMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd));
  }
  httpClient.executeMethod(postMethod);
  LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText());
  return postMethod;
}
 
Example 15
Source File: ESBJAVA_4239_HTTP_SC_HandlingTests.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Test(groups = "wso2.esb", description = "Test whether response HTTP status code getting correctly after callout " +
                                         "mediator successfully execute")
public void testHttpStatusCodeGettingSuccessfully() throws Exception {
    String endpoint = getProxyServiceURLHttp("TestCalloutHTTP_SC");
    String soapRequest = TestConfigurationProvider.getResourceLocation() + "artifacts" + File.separator +
                         "ESB" + File.separator + "mediatorconfig" + File.separator + "callout" +
                         File.separator + "SOAPRequestWithHeader.xml";
    File input = new File(soapRequest);
    PostMethod post = new PostMethod(endpoint);
    RequestEntity entity = new FileRequestEntity(input, "text/xml");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "getQuote");
    HttpClient httpClient = new HttpClient();
    boolean errorLog = false;

    try {
        httpClient.executeMethod(post);

        LogEvent[] logs = logViewerClient.getAllRemoteSystemLogs();
        for (LogEvent logEvent : logs) {
            if (logEvent.getPriority().equals("INFO")) {
                String message = logEvent.getMessage();
                if (message.contains("STATUS-Fault") && message.contains("404 Error: Not Found")) {
                    errorLog = true;
                    break;
                }
            }
        }
    } finally {
        post.releaseConnection();
    }

    if (!errorLog) {
        fail("Response HTTP code not return successfully.");
    }
}
 
Example 16
Source File: NetClient.java    From qingyang with Apache License 2.0 5 votes vote down vote up
private static PostMethod getHttpPost(String url, String userAgent) {
	PostMethod httpPost = new PostMethod(url);
	// 设置请求超时时间
	httpPost.getParams().setSoTimeout(TIMEOUT_CONNECTION);
	httpPost.setRequestHeader("Host", URL.HOST);
	httpPost.setRequestHeader("Connection", "Keep_Alive");
	httpPost.setRequestHeader("User_Agent", userAgent);
	return httpPost;
}
 
Example 17
Source File: ESBJAVA4402MessageWithoutPayloadTestCase.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Send a POST request to the endpoint "without payload" via a proxy service.
 * If chunking is disabled and if there is a content aware mediator in mediation path
 * Message will not send out to the endpoint. With the patch Message should send out
 * so there should be a response at the client side.
 *
 * @throws Exception
 */
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL })
@Test(groups = "wso2.esb")
public void testMessageWithoutContentType() throws Exception {
    // Get target URL
    String strURL = getProxyServiceURLHttp(PROXY_SERVICE_NAME);
    // Get SOAP action
    String strSoapAction = "urn:getQuote";
    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);
    // consult documentation for your web service
    post.setRequestHeader("SOAPAction", strSoapAction);
    // Get HTTP client
    HttpClient httpclient = new HttpClient();

    // Execute request
    try {
        //without the patch POST request without body it not going out from the ESB.
        //if we receive any response from backend test is successful.
        int result = httpclient.executeMethod(post);
        // Display status code
        log.info("Response status code: " + result);
        // http head method should return a 500 error
        assertTrue(result == 500);
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}
 
Example 18
Source File: HttpClientUtil.java    From AndroidRobot with Apache License 2.0 4 votes vote down vote up
/**
 * @param url
 * @param queryString 类似a=b&c=d 形式的参数
 * 
 * @param obj   发送到服务器的对象。
 *     
 * @return 服务器返回到客户端的对象。
 * @throws IOException
 */
public static String httpObjRequest(String url, Object obj, String queryString ) throws IOException
{
	String response = null;
	HttpClient client = new HttpClient();
    
    PostMethod post = new PostMethod(url);
    
    post.setQueryString(queryString);

    post.setRequestHeader("Content-Type", "application/octet-stream");

    java.io.ByteArrayOutputStream bOut = new java.io.ByteArrayOutputStream(1024);
    java.io.ByteArrayInputStream bInput = null;
    java.io.ObjectOutputStream out = null;
    
    try
    {
        out = new java.io.ObjectOutputStream(bOut);

        out.writeObject(obj);

        out.flush();
        out.close();

        out = null;

        bInput = new java.io.ByteArrayInputStream(bOut.toByteArray());

        RequestEntity re = new InputStreamRequestEntity(bInput);
        post.setRequestEntity(re);

        client.executeMethod(post);
        response = post.getResponseBodyAsString();
        System.out.println("URI:" + post.getURI());
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally
    {
        if (out != null)
        {
            out.close();
            out = null;

        }

        if (bInput != null)
        {
            bInput.close();
            bInput = null;

        }
        //释放连接
        post.releaseConnection();
    }

    return response;

}
 
Example 19
Source File: HttpClientUtils.java    From BigApp_Discuz_Android with Apache License 2.0 4 votes vote down vote up
public static String httpPost(String url, Map paramMap, String code) {
    ZogUtils.printLog(HttpClientUtils.class, "request url: " + url);
    String content = null;
    if (url == null || url.trim().length() == 0 || paramMap == null
            || paramMap.isEmpty())
        return null;
    HttpClient httpClient = new HttpClient();
    PostMethod method = new PostMethod(url);

    method.setRequestHeader("Content-Type",
            "application/x-www-form-urlencoded;charset=utf-8");

    Iterator it = paramMap.keySet().iterator();

    while (it.hasNext()) {
        String key = it.next() + "";
        Object o = paramMap.get(key);
        if (o != null && o instanceof String) {
            method.addParameter(new NameValuePair(key, o.toString()));
        }

        System.out.println(key + ":" + o);
        method.addParameter(new NameValuePair(key, o.toString()));

    }
    try {
        httpClient.executeMethod(method);
        ZogUtils.printLog(HttpClientUtils.class, method.getStatusLine()
                + "");
        content = new String(method.getResponseBody(), code);

    } catch (Exception e) {
        ZogUtils.printLog(HttpClientUtils.class, "time out");
        e.printStackTrace();
    } finally {
        if (method != null)
            method.releaseConnection();
        method = null;
        httpClient = null;
    }
    return content;

}
 
Example 20
Source File: OAuth2Client.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
public String getToken(String id, String password) {
	logger.debug("IN");
	try {
		HttpClient client = getHttpClient();
		String url = config.getProperty("REST_BASE_URL") + config.getProperty("TOKEN_PATH");
		PostMethod httppost = new PostMethod(url);
		httppost.setRequestHeader("Content-Type", "application/json");

		String body = "{\r\n";
		body += "    \"auth\": {\r\n";
		body += "        \"identity\": {\r\n";
		body += "            \"methods\": [\r\n";
		body += "                \"password\"\r\n";
		body += "            ],\r\n";
		body += "            \"password\": {\r\n";
		body += "                \"user\": {\r\n";
		body += "                    \"id\": \"" + id + "\",\r\n";
		body += "                    \"password\": \"" + password + "\"\r\n";
		body += "                }\r\n";
		body += "            }\r\n";
		body += "        }\r\n";
		body += "    }\r\n";
		body += "}";

		httppost.setRequestBody(body);

		int statusCode = client.executeMethod(httppost);

		if (statusCode != HttpStatus.SC_CREATED) {
			logger.error("Error while getting access token from IdM REST API: server returned statusCode = " + statusCode);

			byte[] response = httppost.getResponseBody();
			LogMF.error(logger, "Server response is:\n{0}", new Object[] { new String(response) });

			throw new SpagoBIRuntimeException("Error while getting access token from IdM REST API: server returned statusCode = " + statusCode);
		}

		return httppost.getResponseHeader("X-Subject-Token").getValue();
	} catch (Exception e) {
		throw new SpagoBIRuntimeException("Error while trying to get token from IdM REST API", e);
	} finally {
		logger.debug("OUT");
	}
}