I'm trying to connect with monit web service api (Restful Services), using the following code:
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://localhost:2812/z_security_check");
NameValuePair[] credentials = {
new BasicNameValuePair("z_username", "admin"),
new BasicNameValuePair("z_password", "monit"),
new BasicNameValuePair("z_csrf_protection", "off")
};
List<NameValuePair> body = Arrays.asList(credentials);
httpPost.setEntity(new UrlEncodedFormEntity(body));
HttpResponse response = client.execute(httpPost);
System.out.println("Post parameters : " + httpPost.getEntity().getContent());
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());
But always I have the same answer:
Post parameters : java.io.ByteArrayInputStream#79d0569b
Response Code : 401
<html><head><title>401 Unauthorized</title></head><body bgcolor=#FFFFFF><h2>Unauthorized</h2>You are not authorized to access monit. Either you supplied the wrong credentials (e.g. bad password), or your browser doesn't understand how to supply the credentials required<hr><a href='http://mmonit.com/monit/'><font size=-1>monit 5.14</font></a></body></html>
Process finished with exit code 0
but when I enter via browser (http: // localhost: 2812 /) asked me the credentials and displays the information correctly
Apparently the web service of monit is available only in the paid version M/Monit, I solve it by making a Web Scraping with jsup of the main page and got the necessary data
Related
For UI automation testing, I need to do REST Api calls, to get the response. I am passing session id into the HEADER by request.setheader, but I recieved response as :
{"result":{"success":false,"httpCode":200,"errorCode":"INVALID_SESSION_ID","errorMessage":"Session ID not provided... Kindly Login !!"}}
I have tried displaying session id and it seems to be fine, What I don't understand is, why it is not been passed to the API. Below is the code:
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(getUrl);
SessionId SessionId = ((FirefoxDriver)driver).getSessionId();
request.setHeader("Cookie", SessionId.toString());
HttpResponse response = httpClient.execute(request);
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK)
{
throw new Exception(response.getStatusLine().getReasonPhrase());
}
StringBuilder sb = new StringBuilder();
String s;
while(true )
{
s = buf.readLine();
if(s==null || s.length()==0)
break;
sb.append(s);
}
buf.close();
ips.close();
System.out.println("After parsing: "+sb.toString());
Output:
After parsing: strong text
{"result":{"success":false,"httpCode":200,"errorCode":"INVALID_SESSION_ID","errorMessage":"Session ID not provided... Kindly Login !!"}}
Here is the solution:
changed,
request.setHeader("Cookie", SessionId.toString());
to
request.setHeader("sessionId", SessionId.toString());
This was mentioned in the API document given by API team.
Then the session ID is given as output from previous API call, which needs to be passed in the subsequent api calls. I had no idea about this, since I am new to API testing. Hope my answer helps someone in similar situation!!
I am making desktop app in java for instagram right now and i don't know how to get code from callback url. My app is desktop so my REDIRECT-URI is http://instagram.com. So in my app i send a request to https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code and get redirected to instagram.com?code=CODE. And also forgot to mention, I get a code once by my hands a i gave all permissions. So now then i make request i redirected straightly to URL with code.
How do i get code from callback uri in program in java? This is my code:
static void GetCode()
{
try {
String url = "https://api.instagram.com/oauth/authorize/?client_id=" + ClientId + "&redirect_uri=" + BackUri + "&response_type=code&scope=likes+comments+relationships";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
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());
}
catch(Exception e)
{
System.out.print("GET CODE ERROR->"+e.toString());
}
}
Change REDIRECT_URI to http://localhost. So the actual 'redirection' code should be done on your side. And you can parse value of argument code. Also look at the answers to this question. This will help you to grab URI with the code.
How do I do a HTTP GET POST PUT DELETE Request using Java?
I'm using CouchDB and I can post data using cUrl into the database. How do I do the same thing using Java however I cannot find any information on this with good documentation.
curl -X PUT http://anna:secret#127.0.0.1:5984/somedatabase/
Could some please change this cUrl request to Java. Otherwise please recommend me libraries to do so.
Thank You.
You can use HttpClient by Apache.
Here is an example usage of how to call a POST request
String url = "https://your.url.to.post.to/";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("param1", "value1"));
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);
}
I do recommend that you check this article for more examples.
I am using Cleartrip Flight API to get flight fare details. When request the URL with API key, i am getting "Not authorized to access the service" error. Here is my Java code using Apache HttpComponents
HttpHost proxy = new HttpHost("My IP", Port No, "http");
String url = "https://api.cleartrip.com/air/1.0/search?from=BOM&to=DEL&depart-date=2013-06-06&return-date=2013-06-06";
//String url = "http://www.google.com/search?q=developer";
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("X-CT-API-KEY", "My API Key");
request.addHeader("User-Agent", "Mozilla/5.0");
System.out.println(" header "+request.getHeaders("X-CT-API-KEY")[0]);
HttpResponse response = client.execute(request);
System.out.println("\nSending 'GET' request to URL : " + url);
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());
}
Can anyone help me !!!
Even i had the same issue. Later i came to know that all the api (which you get during singn up process) are blocked by default. You have to write a mail to api.support#cleartrip.com
They will ask your company details, business model and business case. If they are satisfied with those details then they will unblock your api key.
Since my project is for my final semester they have rejected my api key query.
Here i am sharing my java code. So that it might be useful for some one.
HttpClient client = new DefaultHttpClient();
String getURL =URL;
Log.d("URL",getURL);
HttpGet get = new HttpGet(getURL);
get.setHeader("X-CT-API-KEY", (my api key));
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null)
{
Log.i("GET ", EntityUtils.toString(resEntityGet));
}
Since i was not authorized to use this api i got the following response.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><faults xmlns="http://www.cleartrip.com/apigateway/common"><fault><fault-message>Not authorized to access the service</fault-message></fault></faults>
HTTP URL is as follows
https://api.cleartrip.com/air/1.0/search?from=BOM&to=DEL&depart-date=2013-11-11&return-date=2013-12-12
I have searched for a while and I am not finding a clear answer. I am trying to log into a webstie.
https://hrlink.healthnet.com/
This website redirects to a login page that is not consitent. I have to post my login credentials to the redirected URL.
Im am trying to code this in Java but I do not understand how to get the URL from the response. It may look a bit messy but I have it this way while I am testing.
HttpGet httpget = new HttpGet("https://hrlink.healthnet.com/");
HttpResponse response = httpclient.execute(httpget);HttpEntity entity = response.getEntity();
String redirectURL = "";
for(org.apache.http.Header header : response.getHeaders("Location")) {
redirectURL += "Location: " + header.getValue()) + "\r\n";
}
InputStream is;
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String result = sb.toString();
I know i get redirected because my result string shows be the actual login page but I am not able to get the new URL.
In FireFox I am using TamperData. When I navigate to this website https://hrlink.healthnet.com/ I have a GET with a 302 - Found and the Location of the Login Page. Then another GET to the actual Login Page
Any help is greatly appreciated thank you.
Check out w3c documentation:
10.3.3 302 Found
The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).
If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.
One solution is to use POST method to break auto-redirecting at client side:
HttpPost request1 = new HttpPost("https://hrlink.healthnet.com/");
HttpResponse response1 = httpclient.execute(request1);
// expect a 302 response.
if (response1.getStatusLine().getStatusCode() == 302) {
String redirectURL = response1.getFirstHeader("Location").getValue();
// no auto-redirecting at client side, need manual send the request.
HttpGet request2 = new HttpGet(redirectURL);
HttpResponse response2 = httpclient.execute(request2);
... ...
}
Hope this helps.