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.
Related
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(...).
I tried searching for this error. There are many results on google for this search but nothing proved useful to me.
This is my web service method
#GET
#Path("/values")
public String test() {
return "{\"x\":5,\"y\":6}";
}
This is my client code
public class Check {
public static void main(String[] args){
String url = "http://localhost:8181/math/webapi/values";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(request);
String value = response.toString();
JSONObject json = new JSONObject(value);
int i = json.getInt("x");
System.out.println(i);
}catch (Exception e) {
e.printStackTrace();
}
}
The above code is a starter code and it is for learning how to use it. If this is solved, I have to apply the knowledge in another application. The client side code, I want to use the logic in android.
EDIT
public class Check {
public static void main(String[] args){
String url = "http://localhost:8181/math/webapi/values";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(request);
InputStream value = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(value));
String jsonValue = br.readLine();
JSONObject json = new JSONObject(jsonValue);
int i = json.getInt("x");
System.out.println(i);
}catch (Exception e) {
e.printStackTrace();
}
}
Fairly certain response.toString doesn't do what you think it does, as it's not listed in the documentation.
I believe you need to use response.getEntity, and then entity.getContent, which gives you an InputStream to read the content from. Then pass that stream into your parser.
Try this code. Use IOUtils as mentioned. it will work.
public class Check {
public static void main(String[] args){
String url = "http://localhost:8181/math/webapi/values";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(request);
InputStream value = response.getEntity().getContent();
String jsonValue = IOUtils.toString(value);
JSONObject json = new JSONObject(jsonValue);
int i = json.getInt("x");
System.out.println(i);
}catch (Exception e) {
e.printStackTrace();
}
}
There is the following code:
private static String doPostRequest(List<NameValuePair> params, String url) throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
return getContentFromInputStream(response.getEntity().getContent());
}
private static String getContentFromInputStream(InputStream is) throws IOException {
String line;
StringBuilder sb=new StringBuilder();
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
while((line=reader.readLine())!=null) {
sb.append(line);
}
reader.close();
return sb.toString();
}
So, how can I add some image (for example, File f) to my POST request? Thanks in advance.
This was part of Servlet 3's "multi part file upload".
You would build up a blob of the image then post it to a Servlet 3 endpoint.
Take a look at the examples here and here
If you plan on using Spring, that has some really nice easy annotations to define your controllers which will work with file upload you can see here
You can use MultipartRequestEntity .
File f = new File(filePath);
PostMethod postMessage = new PostMethod(urlString);
Part[] parts = {
new StringPart("param", "value"),
new FilePart(f.getName(), f)
};
postMessage.setRequestEntity(new MultipartRequestEntity(parts, postMessage.getParams()));
HttpClient client = new HttpClient();
int status = client.executeMethod(postMessage);
I need to send http POST request from mobile android application to the server side applcation.
This request need to contain json message in body and some key-value parametres.
I am try to write this method:
public static String makePostRequest(String url, String body, BasicHttpParams params) throws ClientProtocolException, IOException {
Logger.i(HttpClientAndroid.class, "Make post request");
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(body);
httpPost.setParams(params);
httpPost.setEntity(entity);
HttpResponse response = getHttpClient().execute(httpPost);
return handleResponse(response);
}
Here i set parametres to request throught method setParams and set json body throught setEntity.
But it isn't work.
Can anybody help to me?
You can use a NameValuePair to do this..........
Below is the code from my project where I used NameValuePair to sent the xml data and receive the xml response, this will provide u some idea about how to use it with JSON.
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now",sb+"");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sb.toString());
return sb.toString();
}
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