Liferay logout returns 400 response - java

I am trying to hit the Liferay logout servlet "c/portal/logout" through Java, but it always returns a 400 response:
private void sendPost() throws Exception {
String url = "localhost:8080/c/portal/logout";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}

Assuming your intention is to logout a user's session, the best way is to call sendRedirect on an HttpServletResponse reference
public void myPostAction(ActionRequest request, ActionResponse response) throws Exception {
// ...
response.sendRedirect("/c/portal/logout");
}

Related

Setting up an incoming webhook for Hangouts Chat API with Java?

I followed the example here (Incoming webhook with Python), which sends a simple message to a Hangouts chat room and works as expected
from httplib2 import Http
from json import dumps
def main():
url = 'https://chat.googleapis.com/v1/spaces/AAAAUfABqBU/messages?key=<WEBHOCK-KEY>'
bot_message = {
'text' : 'Hello from Python script!'}
message_headers = { 'Content-Type': 'application/json; charset=UTF-8'}
http_obj = Http()
response = http_obj.request(
uri=url,
method='POST',
headers=message_headers,
body=dumps(bot_message),
)
print(response)
if __name__ == '__main__':
main()
Now I want achive the same simple thing using Java and tried it with this code
private void sendPost() throws IOException {
String url = "https://chat.googleapis.com/v1/spaces/AAAAUfABqBU/messages?key=<WEBHOCK-KEY>";
final HttpClient client = new DefaultHttpClient();
final HttpPost request = new HttpPost(url);
final HttpResponse response = client.execute(request);
request.addHeader("Content-Type", "application/json; charset=UTF-8");
final StringEntity params = new StringEntity("{\"text\":\"Hello from Java!\"}", ContentType.APPLICATION_FORM_URLENCODED);
request.setEntity(params);
final BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
But this leads to an error message saying
{
"error": {
"code": 400,
"message": "Message cannot be empty. Discarding empty create message request in spaces/AAAAUfABqBU.",
"status": "INVALID_ARGUMENT"
}
}
I assume there is something wrong with the way I add the json object. Does anybody see the mistake?
Kind of dump, but moving the line final HttpResponse response = client.execute(request); after setting the request body solves the issue.
private void sendPost() throws IOException {
String url = "https://chat.googleapis.com/v1/spaces/AAAAUfABqBU/messages?key=<WEBHOCK-KEY>";
final HttpClient client = new DefaultHttpClient();
final HttpPost request = new HttpPost(url);
// FROM HERE
request.addHeader("Content-Type", "application/json; charset=UTF-8");
final StringEntity params = new StringEntity("{\"text\":\"Hello from Java!\"}", ContentType.APPLICATION_FORM_URLENCODED);
request.setEntity(params);
// TO HERE
final HttpResponse response = client.execute(request);
final BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
Order sometimes does matter :)

org.springframework.web.HttpRequestMethodNotSupportedException when trying to make POST call ( https://url/test)

## sendPost method to make the POST call. It is fetching the url and also printing the data properly in the below method. ##
Public static void sendPost(String url, String data) throws Exception {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", "Mozilla/5.0");
StringEntity requestEntity = new StringEntity(data);
post.setEntity(requestEntity);
post.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.[`enter link description here`][1]append(line);
}
System.out.println(result.toString());
}
}
#RequestMapping(value="/test", method = RequestMethod.POST)
public #ResponseBody String sendTestData(#RequestBody TestDTO TestData) {
try{
log.info("Data got to ingestion rest: "+TestData);
String jsonData = new Gson().toJson(TestData).toString();
System.out.println("jsonData=="+ jsonData);
boolean result = dataIngestionHandler.insertData(jsonData);
if(result){
return "SUCCESS";
}
}catch(Exception ex) {
log.error("Error while inserting data into the db!!");
return "FAIL" + ex.getMessage();
}
return "FAIL";
}
I am sending the data from the sendPost method to the controller method, but in response it is giving:
405 exception
Exact error
code:{"timestamp":1467696109585,"status":405,"error":"Method Not
Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request
method 'POST' not supported","path":"/test"}.
The entire setup is running fine and data is getting inserted into the db when I run it on localhost. But as soon as I push it to cloud, the following exception comes up

Response code 404 using apache commons

I'm building a wrapper for an API http://www.sptrans.com.br/desenvolvedores/APIOlhoVivo/Documentacao.aspx?1#docApi-autenticacao (it's in portuguese, but you get the idea).
I'm getting response code 404 when making a POST request and I have no idea why.
This is what is being printed:
Response Code : 404 {"Message":"No HTTP resource was found that
matches the request URI
'http://api.olhovivo.sptrans.com.br/v0/Login/Autenticar'."}
public static String executePost() {
CloseableHttpClient client = HttpClientBuilder.create().build();
String targetURL = "http://api.olhovivo.sptrans.com.br/v0/Login/Autenticar";
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("token","3de5ce998806e0c0750b1434e17454b6490ccf0a595f3884795da34460a7e7b3"));
try {
HttpPost post = new HttpPost(targetURL);
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) result.append(line);
System.out.println(result.toString());
return result.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
It looks to me from the API documentation (albeit, I can't read Portugese), that the token needs to be in the URL, not POSTed to it:
POST /Login/Autenticar?token={token}
I think you are POSTing a form to this endpoint.
You should try this:
String targetURL = "http://api.olhovivo.sptrans.com.br/v0/Login/Autenticar?token=3de5ce998806e0c0750b1434e17454b6490ccf0a595f3884795da34460a7e7b3";
And don't call post.setEntity(...).

Read JSON message from HTTP POST request in Java

I am new to Java and to client- server programming.
I am using embedded Jetty, and I'm trying to send a JSON string to some address (http://localhost:7070/json) and then to display the JSON string in that address.
I tried the following code but all I get is null.
Embedded Jetty code:
public static void main(String[] args) throws Exception {
Server server = new Server(7070);
ServletContextHandler handler = new ServletContextHandler(server, "/json");
handler.addServlet(ExampleServlet.class, "/");
server.start();
}
Client side function for sending the Http POST:
public static void sendHttp(){
HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead
try {
HttpPost request = new HttpPost("http://localhost:7070/json");
JSONObject object = new JSONObject();
try {
object.put("name", "MyName");
object.put("age", "26");
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
String message = object.toString();
request.setEntity(new StringEntity(message, "UTF8"));
request.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(request);
// handle response here...
}catch (Exception ex) {
// handle exception here
} finally {
}
}
And Servlet functions:
public class ExampleServlet extends HttpServlet{
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//System.out.println("test get\n");
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//System.out.println("test post\n");
PrintWriter out = resp.getWriter();
String json_str = req.getParameter("name");
out.print(json_str);
}
}
I call the sendHttp() method from a test class, after running the embedded Jetty server code (if that matters).
To get the data from a Post request you need to obtain the content. Try this:
String data = IOUtils.toString(req.getInputStream(), "UTF-8");
You need to read the raw request body as below. Put this inside your doPost method of servlet for reading json from the request:
StringBuilder jsonBuff = new StringBuilder();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jsonBuff.append(line);
} catch (Exception e) { /*error*/ }
System.out.println("Request JSON string :" + jsonBuff.toString());
//write the response here by getting JSON from jasonBuff.toString()
try {
JSONObject jsonObject = JSONObject.fromObject(jb.toString());
out.print(jsonObject.get("name"));//writing output as you did
} catch (ParseException e) {
throw new IOException("Error parsing JSON ");
}
Note : You can access req.getParameter("name"); only when your headers would be like this:
content type: "application/x-www-form-urlencoded"
as in normal html form submission.
Here is my code this works fine
String data = "";
StringBuilder builder = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
data = builder.toString();
JSONObject object = new JSONObject(data);
//or JSONArray array = new JSONArray(data); which ever the one you want
Good luck.....
I have not used jetty but I have done similar comunications with this code (PUT, not POST):
URL url = new URL(desturl);
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
huc.setRequestMethod("PUT");
byte[] postData = null;
int postDataLength;
huc.setDoOutput(true);
postData = data.getBytes( StandardCharsets.UTF_8 );
postDataLength = postData.length;
huc.setRequestProperty( "Content-Type", "application/json");
huc.setRequestProperty( "charset", "utf-8");
huc.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
huc.setUseCaches( false );
huc.connect();
huc.setConnectTimeout(10000);
DataOutputStream wr = new DataOutputStream( huc.getOutputStream());
wr.write( postData );
rd = new BufferedReader(new InputStreamReader(huc.getInputStream()));
retcode = huc.getResponseCode();

How to get parameter on server from POST Url

I am trying to hit some URL using Post Method from client side with some data in the format of "NameValuePair", And receive that data from URL in servlet (server side) for performing some calculation and send back response to the client in JSON fromat.
But I am able to find correct data on Servlet (server)
Hit URL from Client Side
private void sendHTTPSPost() throws Exception {
String url = "http://localhost:8080/test/Registration";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("name", "A"));
urlParameters.add(new BasicNameValuePair("age", "12"));
urlParameters.add(new BasicNameValuePair("sex", "M"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
On Servlet
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String paramName = (String)headerNames.nextElement();
System.out.println("Value of param is ------------------"+paramName);
String paramValue = request.getHeader(paramName);
System.out.println("Value of key is ------------------"+paramValue);
}
}
I tried a lot but not get correct result.
you are missing
post.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
You are getting the headers from the request you must use the request.getParameterNames() to get the parameters.
You can use -
requests.getParameter("name"); //returns A
requests.getParameter("age"); //returns 12
requests.getParameter("sex"); //returns M

Categories