Crypt
Crypt

Reputation: 189

Calling a Sling Servlet From java code

I am trying to call a servlet via HTTP POST from my java code.Below is my code

private void sendRequest(String Url)
{
  //Url contains all the POST parameters

try {

        URL url = new URL(Url);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();           
        connection.setDoOutput(true); 
        connection.setInstanceFollowRedirects(false); 
        connection.setRequestMethod("GET"); 
        connection.setRequestProperty("Content-Type", "text/plain"); 
        connection.setRequestProperty("charset", "utf-8");
        connection.connect();
        connection.disconnect();

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

}

But the request is not going to the servlet. I tried to reach the URL via browser and it's working fine.Am I missing something or is there any problem with the code.Please help.

Upvotes: 1

Views: 1911

Answers (2)

santiagozky
santiagozky

Reputation: 2539

If what you are trying to do is to process a request through a running sling, you might want to check the Sling Request Processor . you can process request to the Sling engine with that service.

Additionaly, if you are using CQ, you can use the Request Response Factory to create the request that you pass to the request processor

Upvotes: 1

BalusC
BalusC

Reputation: 1108852

You're nowhere actually sending the HTTP request. Only connecting/disconnecting is not sufficient. In case of URLConnection the HTTP request will only be sent when your code starts to obtain information about the HTTP response, such as response status, headers and/or body.

Replace those unnecessary connect() and disconnect() lines by e.g.

int responseStatusCode = connection.getResponseCode(); // 200 == OK.

or

InputStream responseBody = connection.getInputStream();
// Consume it.

See also:

Upvotes: 0

Related Questions