Response code 404 using apache commons - java

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(...).

Related

POST API automation using selenium with JSON Header

I want to automate REST API using selenium(java), is it possible ? if it have header and body part in json form
In Java you can use ApacheHttpClient for example lerned from https://www.mkyong.com/java/apache-httpclient-examples/
For instance a method in ApacheHttpClientPost could be like that:
public static String post(String tokenMobile, String method, String version, String body) throws Exception{
try {
HttpClient httpClient = HttpClientBuilder.create().build();
URIBuilder builder = new URIBuilder();
builder.setScheme("https").setHost(host).setPath(method)
.setParameter("", ""); //Params
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
HttpPost postRequest = new HttpPost(httpget.getURI()); //Header
postRequest.addHeader("Content-Type", "application/json");
postRequest.addHeader("version", version);
postRequest.addHeader("Authorization", "Bearer "+tokenMobile);
StringEntity input = new StringEntity(body); //Body in json
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
StringBuilder stringBuilder = new StringBuilder();
outputs = stringBuilder.append(output).toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return outputs;
}
Selenium is a tool which is designed for automation of UI or e2e test cases. You can integrate the Selenium test case with API test cases but that is always a bad idea.
Try something like Rest-Assured, Postman, HTTPClient if you want to automate the API test cases.

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

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

Set cookie from HTTP Request

I have get a correct login using HttpRequest to work. It prints the correct html form of the logn page in my toast (just for testing). Now I want to set a cookie from that request. How is this possible?
If it necessary I can provide some code.
I already know about the CookieManager class, but how can I successfully do it?
Thanks in advance!
My code:
public String getPostRequest(String url, String user, String pass) {
HttpClient postClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("login", user));
nameValuePairs.add(new BasicNameValuePair("pass", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
response = postClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
instream.close();
return result;
}
}
} catch (Exception e) {}
Toast.makeText(getApplicationContext(),
"Connection failed",
Toast.LENGTH_SHORT).show();
return null;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Well, this is pretty much it. convertStreamToString() function converts the InputStream into a String (plain HTML code), which I "toast" out to just test it (so it work), so the code is working though. Now to set the cookie. :-)
This is what I've reached for now:
// inside my if (entity != null) statement
List<Cookie> cookies = postClient.getCookieStore().getCookies();
String result = cookies.get(1).toString();
return result;
When I have logged in, the CookieList id 1 contains a value, otherwise the value is standard. So for now I know the difference in value, but how can I continue?
I think Android ships with Apache HttpClient 4.0.
You can check Chapter 3. HTTP state management topic from HttpClient Tutorial.
You can also refer similar questions on SO:
Android project using httpclient --> http.client (apache), post/get method
How do I manage cookies with HttpClient in Android and/or Java?
Also Check this example for usage: http://svn.apache.org/repos/asf/httpcomponents/httpclient/branches/4.0.x/httpclient/src/examples/org/apache/http/examples/client/ClientFormLogin.java

Categories