How to Send API header request through Selenium and get response back - java

I have to automate API through selenium+TestNG (Java). I know its not a good habit to automate APIs using selenium code but still I have got this to do.
Scenario - there is a login API and have to send the email and password and get response back (response code 200). Also can we print the response information also?

If you are working on java you can use JAVA socket libraries for the same:
Here are the sample code for POST API:
URL obj = new URL(url);
con = (HttpsURLConnection) obj.openConnection();
// add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
String urlParameters = "j_username=" + user + "&j_password=" + pass
+ "";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
For GET API:
obj = new URL(url);
obj.openConnection();
con = (HttpsURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
CookieHandler.setDefault(new CookieManager());
// add request header
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.8l");
con.setRequestProperty("Accept", "*/*");
con.setRequestProperty(
"Cookie",
"BIGipServerPRODCAN-Default=423078080.2087.0000; __utma=44365112.1659763098.1418886605.1427784911.1441869730.4; __utmc=44365112; __utmz=44365112.1427784911.3.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); JSESSIONID="
+ cookieValue);
responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
File file = new File(prop.getFilePath() + "//XMLs//" + fileName
+ ".xml");
file.delete();
FileWriter fstream = new FileWriter(prop.getFilePath() + "//XMLs//"
+ fileName + ".xml", true);
BufferedWriter out = new BufferedWriter(fstream);
while ((inputLine = in.readLine()) != null) {
out.write(inputLine.toString());
out.newLine();
response.append(inputLine);
}
in.close();
out.close();`

Related

Send JSON data through POST in Java

I have this code to send JSON data (passed as a string) to the server (This code works when English characters are to be sent as values in dataJSON as far as I tested):
private static String sendPost(String url, String dataJSON) throws Exception {
System.out.println("Data to send: " + dataJSON);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String type = "application/json;charset=utf-8";
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Length", String.valueOf(dataJSON.getBytes("UTF-8").length));
con.setRequestProperty("Content-Type", type);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeUTF(dataJSON);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.print("Response string from POST: " + response.toString() + "\n");
return response.toString();
}
Problem is I don't get correct response, which I get for example using DHC Restlet Client.
The problem is I think the dataJSON must be encoded in UTF8. That's how the server expects it most likely.
But it seems I have some problem in code the way I try to convert it and send it.
Can someone help me send data in body as UTF8 string in above example?
I think I solved with this approach:
private static String sendPost2(String urlStr, String dataJSON) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
os.write(dataJSON.getBytes("UTF-8"));
os.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = new BufferedReader(new InputStreamReader(in)) .lines().collect(Collectors.joining("\n"));
in.close();
conn.disconnect();
return result;
}
Please suggest alternative if you see problem with it.

Access website through vpnbook.com

I am working on application to access a web page through vpnbook.com.
My code is sending post request to URL "https://webproxy.vpnbook.com/includes/process.php?action=update" with post body as "u=yahoo.com&webproxylocation=random"
i am getting response code 302. and HTTP response header contains location
"Location=[http://www.vpnbook.com/webproxy]"
But same request was getting correct correct result when opening through web browser.
result contains header response
"Location:https://usproxy.vpnbook.com/browse.phpu=DWnjEwVwhlG5GQhW&b=0&f=norefer"
please tell me what is going wrong in my code.
try{
URL url = new URL("https://webproxy.vpnbook.com/includes/process.php?action=update");
HttpsURLConnection c = (HttpsURLConnection) url.openConnection();
c.setRequestProperty("User-Agent", USER_AGENT);
c.setRequestProperty("Accept-Language", ACCEPT_LANG);
c.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
c.setRequestProperty("Host", "webproxy.vpnbook.com");
c.setRequestProperty("Origin", "http://www.vpnbook.com");
c.setRequestProperty("Referer", "http://www.vpnbook.com/webproxy");
c.setRequestMethod("POST");
c.setDoInput(true);
c.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(c.getOutputStream());
wr.writeBytes("u=yahoo.com&webproxylocation=random");
wr.flush();
wr.close();
int responseCode = c.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
System.out.println("Response headers : " + c.getHeaderFields());
Map<String, List<String>> resHdr = c.getHeaderFields();
if( resHdr.containsKey("Set-Cookie") ){
cookies=resHdr.get("Set-Cookie").toString();
cookies = cookies.replaceAll("\\[|\\]", "");
System.out.println(cookies);
}
BufferedReader in =
new BufferedReader(new InputStreamReader(c.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response);
}catch(Exception ex) { ex.printStackTrace(); }

Sending post request to website

I'm trying to use java to log in to a website and then eventually retrieve the cookie in order to gain access to information on the site. It seems my post request is working but I am receiving a response code of 500. I was wondering if this is because I have formatted the post data incorrectly
When using the website it says the post is formatted as below
{userName: "dfh", password: "suyj"}
In my code I have used this
String urlParameters = "userName:dfh,Password:suyj";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
Am I right in thinking this could be the issue, and if so how can I correct my post data format?
Below is my whole code
public class post {
public static void main(String[] args) throws IOException {
final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0";
String url = "website";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Accept-Encoding", "gzip, deflate");
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("X-Requested-With", "XMLHttpRequest");
con.setRequestProperty("Referer", "https://extbasicph05.podc.sl.edst.ibm.com/FFAMobileRelay/");
con.setRequestProperty("Content-Length", "64");
con.setRequestProperty("Connection", "keep-alive");
con.setRequestProperty("Referer", "https://extbasicph05.podc.sl.edst.ibm.com/FFAMobileRelay/");
con.setRequestProperty("Cookies", "UnicaNIODID=KGew34gcvZ5-Y2NoBQr; mmid=-1658088866%7CKAAAAAr15Tc8FgsAAA%3D%3D; mmcore.pd=1484641984%7CejEyAAoBQvXlNzwWCxPPXGheAVibftSXgNJIDwAAADoOVvoDstFIAAAAAP//////////AAZEaXJlY3QBFgwIAAYABQAAAAAAAP+MAACAigAA/4wAAAIAxDEAAABFBVUW6QsA/////wHpCxoM//83AAAAAAAAAAOSfwAAusgAAJN/AAAgyAAAlH8AACHIAAABIYAAAAIAAADVNgAAAPcCB+70CwD/////AfQLHQz//60CAAEAAAAAAX+KAAAp2gAAAoCKAABAWBAAgYoAALMAAAAAAAABRQ%3D%3D; mmcore.srv=ldnvwcgus03; IBM_W3SSO_ACCESS=w3-03.sso.ibm.com; CoreID6=32675392371714128784599&ci=51040000|IBMTEST_51040000|IBMTESTW3_50200000|IBMTESTWWW; CoreM_State=75~-1~-1~-1~-1~3~3~5~3~3~7~7~|~~|~~|~~|~||||||~|~~|~~|~~|~~|~~|~~|~~|~; CoreM_State_Content=6~|~EE9EDB09923CD77F~|~0; PrefID=222-11978519; CSList=23427744/17540903,0/0,0/0,0/0,0/0; _ga=GA1.2.233924805.1433836377; mmcore.tst=0.169; ibmSurvey=1435758135373; 50200000_clogin=v=1&l=1435758136&e=1435760174616");
String urlParameters = "userName:dfh,Password:suyj";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
System.out.println(con.getErrorStream());
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}
You have already found out your problem. Just fix it...
Instead of String urlParameters = "userName:dfh,Password:suyj";, use
String urlParameters = "{userName:\"dfh\",Password:\"suyj\"}";
Though I believe your server expects JSON formatted post parameter. In that case you should use,
String urlParameters = "{\"userName\":\"dfh\",\"Password\":\"suyj\"}";
Or use a JSON parser to create the parameters.

In HttpURLConnection Why don't JSONObject as Params work but String as Params are working

I am using HttpUrlConnection to post some data to my server here is the function:
private String register(String myurl) throws IOException {
String resp = null;
try {
JSONObject parameters = new JSONObject();
// parameters.put("jsonArray", ((makeJSON())));
parameters.put("key", "key");//getencryptkey());
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setReadTimeout(10000 /* milliseconds *///);
// conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(parameters.toString());
writer.close();
out.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("strngbuffr" + response.toString());
resp = response.toString();
} catch (Exception exception) {
System.out.println("Exception: " + exception);
}
System.out.println("rsp"+ resp.toString());
return resp.toString();
}
I get the response code as 200, which means connection is okay however I get empty variables on PHP side, what can be wrong here?
Earlier I was sending a JSON array too but just to test functonality I commented that out now I am only sending one variable key as "key"
Its amazing to see, this sample code works - sans the JSON array and the key value pairs:
private String sendPost(String url) throws Exception {
String USER_AGENT = "Mozilla/5.0";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String urlParameters ="sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println("rvsp"+response.toString());
return response.toString();
}
So it boils down to replacing this:
JSONObject parameters = new JSONObject();
parameters.put("jsonArray", new JSONArray(Arrays.asList(makeJSON())));
parameters.put("key", getencryptkey());
by this:
String urlParameters ="jArr="+makeJSON()+"Key="+getencryptkey();
and I am still curious.
I reckon the problem here is not at the Java side, If the parameters is of fixed type like in json in your case, the JSON Object as POST params method will work if collected this way on the php side:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
print_r($obj);
print_r("this is a test response");
?>
The problem here was not with the Java side, it was with the php side, the JSON Object as POST params method will work if collected this way on the php side:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
print_r($obj);
print_r("this is a test");
?>

OpenId Connect to Google gives me Http 400

Im trying to access to Google APIs using OAuth 2.0
but i always receive the http 400 when i try to get the token
I'm using Tomcat8 with Java SDK 8
And i don't know what is wrong.
private void sendPost(
final String code,
final String clientId,
final String clientSecret,
final String redirectUri,
final String grantType) throws Exception {
String url = "https://accounts.google.com/o/oauth2/token";
StringBuffer strb = new StringBuffer();
strb.append("code=" + code);
strb.append("&client_id=" + clientId);
strb.append("&client_secret=" + clientSecret);
strb.append("&redirect_uri=" + redirectUri);
strb.append("&grant_type=" + grantType);
String urlParameters = strb.toString();
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", String.valueOf(urlParameters.length()));
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
}
My output is the following it seems that all parameters are ok.
Sending 'POST' request to URL : https://accounts.google.com/o/oauth2/token
Post parameters : code=<code>.InoAg9JcLi0boiIBeO6P2m94pmoskwI&client_id=<clientid>.apps.googleusercontent.com&client_secret=<secret>&redirect_uri=http://localhost:8080/Oauth/connect&grant_type=authorization_code
Response Code : 400
you'd want to url-encode the parameters
I don't think Google supports redirect_uri's pointing to "localhost" anymore so that would suggest that you got the "code" on a different redirect_uri than the one presented on the token endpoint request

Categories