This is what my URL look like:
https://localhost.com.ua/oauth/authorize?client_id=SS&response_type=code&scope=N_FULL&access_type=offline&redirect_uri=http://localhost/
Upon posting that in java (http post request), it'll be re-directed to this URI:
https://kuma.ruto/v1/0auth/grant?state=some&code=YrnYdnHdY
How can I obtain the re-directed URI and get the code value?
Below is the code snippet:
String data = "email=p#f.com&password=Airtel#2017";
URL url = new URL("https://login.something.com/v1/oauth/authorize?response_type=code&state=none&email=p#f.com&client_id=jkhsdhaskfhdash&password=Airtel#2017&redirect_uri=https://login.something.com&code=none");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(
con.getOutputStream());
writer.write(data);
InputStream is = con.getInputStream();
System.out.println( "redirected url: " + con.getURL() );
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
System.out.println( "redirected url2: " + con.getURL() );
String st = null;
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
st += output;
}
Spdfast111 test = new Spdfast111();
Map<String, String> map=test.getFormParams(st);
URL url1 = new URL("https://login.something.com/v1/oauth/grant?value_one="+map.get("value_one")+"&value_two="+map.get("value_two")+"redirected_uri=https://login.something.com/v1/oauth/token");
System.out.println("==========================="+url1);
HttpURLConnection con1 = (HttpURLConnection) url1.openConnection();
System.out.println( "orignal url: " + con1.getURL() );
con1.connect();
System.out.println( "connected url: " + con1.getURL() );
InputStream is1 = connn.getInputStream();
System.out.println( "redirected url: " + con1.getURL() );
is1.close();
You can take a look at the following example:
https://github.com/mconf/bbb-java/blob/master/src/main/java/org/mconf/bbb/api/JoinServiceBase.java#L151
HttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(joinUrl);
HttpContext context = new BasicHttpContext();
HttpResponse httpResponse = client.execute(method, context);
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
log.debug("HTTP GET {} return {}", joinUrl, httpResponse.getStatusLine().getStatusCode());
HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
if (!currentReq.getURI().getPath().equals("/client/BigBlueButton.html")) {
log.warn("It was redirected to {} instead of /client/BigBlueButton.html: the server was branded" +
" and the HTML name was changed, or it's an error. However, it will continue processing", currentReq.getURI().getPath());
}
HttpHost currentHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
String enterUrl = currentHost.toURI() + "/bigbluebutton/api/enter";
How about this example?:
// loop until no more redirections are
for (;;) {
if (Thread.currentThread().isInterrupted()) {
return null;
}
if(proxy != null) {
ucn = downloadURL.openConnection(proxy);
} else {
ucn = downloadURL.openConnection();
}
HttpURLConnection hucn = doConfigureURLConnection(ucn);
if(Thread.currentThread().isInterrupted())
return null;
ucn.connect();
int rc = hucn.getResponseCode();
boolean isRedirect =
rc == HttpURLConnection.HTTP_MOVED_TEMP ||
rc == HttpURLConnection.HTTP_MOVED_PERM;
if (!isRedirect) {
break;
}
String addr = hucn.getHeaderField(HTTP_REDIRECT_LOCATION);
URL newURL = new URL(addr);
if (!downloadURL.getProtocol().equalsIgnoreCase(newURL.getProtocol())) {
throw new ResourceRedirectException(newURL);
}
downloadURL = newURL;
}
Full code here: http://code.openhub.net/file?fid=eLvMdX5b01HDEtWkU2TEPg13uu0&cid=xJ52R73llJU&s=Obtaining%20the%20location%20of%20the%20redirected%20uri&pp=0&fl=Java&ff=1&filterChecked=true&fp=1141&mp,=1&ml=1&me=1&md=1&projSelected=true#L0
Related
I need to call a database api https://hosturl/query?apiToken=authenticated_API_Token
and need to pass request payload :-
{ "\r\n" +
"\"filterString\": \"([62wUXYCDt0WnOnO18psHbQ.ZPyw3IUxsUWvywjWCEuAdQ.QEfefkYB5EqgogjWCEuoBg] ge Today() and Date([62wUXYCDt0WnOnO18psHbQ.ZPyw3IUxsUWvywjWCEuAdQ.KR-iuFdqYUCnjgjW8zNMoQ]) le Today())\",\r\n"
"\r\n" +
"}
It will give a response with post call.
I tried it with JS:-
xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "https://hosturl/query?apiToken=someToken", true);
xmlHttp.setRequestHeader("Content-Type", "application/json");
xmlHttp.send("{ "\r\n" +
"\"filterString\": \"([62wUXYCDt0WnOnO18psHbQ.ZPyw3IUxsUWvywjWCEuAdQ.QEfefkYB5EqgogjWCEuoBg] ge Today() and Date([62wUXYCDt0WnOnO18psHbQ.ZPyw3IUxsUWvywjWCEuAdQ.KR-iuFdqYUCnjgjW8zNMoQ]) le Today())\",\r\n"
"\r\n" +
"}");
Here I am getting proper response.
But when I am trying with java getting connection timeout.
final URL url = new URL(https://hosturl/query?apiToken=someToken);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
final String payLoad ="{ "\r\n" +
"\"filterString\": \"([62wUXYCDt0WnOnO18psHbQ.ZPyw3IUxsUWvywjWCEuAdQ.QEfefkYB5EqgogjWCEuoBg] ge Today() and Date([62wUXYCDt0WnOnO18psHbQ.ZPyw3IUxsUWvywjWCEuAdQ.KR-iuFdqYUCnjgjW8zNMoQ]) le Today())\",\r\n"
"\r\n" +
"}";
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type","application/json") ;
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Length", Integer.toString(payLoad.length()));
conn.setUseCaches(false);
final java.io.OutputStream os = conn.getOutputStream();
try (java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(os);) {
wr.write(data);
wr.flush();
}
final int responseCode = conn.getResponseCode();
if (responseCode == 200 || responseCode == 201) {
final StringBuilder response = new StringBuilder();
try (java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
responseString = response.toString();
} else {
}
conn.disconnect();
} catch (final Exception ex) {
LOG.error("Exception ", ex);
} finally {
if (conn != null) {
conn.disconnect();
}
}
What can be the reason?
i'm trying to add the following headers to a rest Post call... it works in plain Java but i'm trying to re-write it using the Jersey client library... When I make the post with Jersey I get an error code which isn't listed in the API documentation so i know it must just be a small issue like a missing header... Any idea what i'm doing wrong in the bottom function?
Plain Java add headers function that works:
private void SetDefaultHeaders(HttpURLConnection conn) {
setRequestProperty(conn, "Accept", "*");
setRequestProperty(conn, "Content-Type", "application/x-www-form-urlencoded");
}
Jersey code:
public void logIn(String email, String password) {
if (email != "" && email != null && password != "" && password != null) {
try {
StringBuilder sb = new StringBuilder();
sb.append(Settings.WIFIPLUG_URL);
sb.append("/user_login");
MultivaluedMap<String, String> body = new MultivaluedMapImpl();
body.add("username=", email);
body.add("password=", password);
System.out.println("login url: " + sb.toString());
WebResource webResource = Client.create(new DefaultClientConfig()).resource(sb.toString());
WebResource.Builder builder = webResource.accept("*");
builder.type("application/x-www-form-urlencoded");
ClientResponse response = builder.post(ClientResponse.class, body);
if (response.getStatus() != 200) {
throw new RuntimeException("failed: http error code " + response.getStatus());
}
System.out.println("Response from server: " + response.getEntity(String.class));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Full vanilla java login function:
public String postUserLogin(String username, String password) {
String result = "";
// URL for API to login
String url = "https://wifiplugapi.co.uk:3081/zcloud/api/user_login";
String requestParams = "username=" + username + "&password=" + password;
try {
URL obj = new URL(url);
System.out.println("login url: " + obj);
// Opens the connection
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// Send POST request
con.setDoOutput(true);
con.setDoInput(true);
// Request Headers
con.setRequestMethod("POST");
// Sets all the headers
SetDefaultHeaders(con);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
wr.write(requestParams);// adds values to the request
wr.flush();
wr.close();
// Handles the response
StringBuilder sb = new StringBuilder();
int responseCode = con.getResponseCode();
if (responseCode == 200) {
// if the request was successful OK = 200
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
// Returns Token
} else {
// If the request was bad, reason will be printed
result = "Error, login request failed";
throw new RuntimeException("Failed : HTTP error code : " + con.getResponseCode());
}
result = sb.toString();
// JSON Parser
JsonParser parser = new JsonParser();
JsonObject resultObj = parser.parse(result).getAsJsonObject();
con.disconnect();
if (resultObj.get("token") != null) {
result = (resultObj.get("token")).toString();
System.out.println("JSONObject Result (token): " + result);
} else {
System.out.println("result = " + result);
}
} catch (Exception e) {
e.printStackTrace();
}
// returns token value in string ie. fdg573gb3789gv923378gy83g3
result = result.replaceAll("\"", "");
return result;
}
You shouldn't have the = in the key when doing body.add. It will be added for you
MultivaluedMap<String, String> body = new MultivaluedMapImpl();
body.add("username=", email); // remove the =
body.add("password=", password); // remove the =
I have this C# working example
void Main()
{
string r = String.Format("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><TrackMobileApp xmlns=\" url \" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><device>test device</device><imei>000000</imei><ipAddress>192.168.1.1</ipAddress><timeStamp>{0}</timeStamp></TrackMobileApp></s:Body></s:Envelope>", DateTime.Now.ToString("o"));
HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create("asmx url");
wr.ProtocolVersion = HttpVersion.Version11;
wr.Headers.Add("SOAPAction", "\"soap action url\"");
wr.Method = "POST";
wr.ContentType = "text/xml;charset=utf-8";
using (StreamWriter sw = new StreamWriter(wr.GetRequestStream()))
{
sw.Write(r);
}
HttpWebResponse rs = (HttpWebResponse)wr.GetResponse();
if (rs.StatusCode == HttpStatusCode.OK)
{
XmlDocument xd = new XmlDocument();
using (StreamReader sr = new StreamReader(rs.GetResponseStream()))
{
xd.LoadXml(sr.ReadToEnd());
xd.InnerXml.Dump();
}
}
}
I've tried this in android:
private class DownloadTask extends AsyncTask<String, Void, String> {
private String downloadContent(String myurl) throws IOException {
InputStream is = null;
int length = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestProperty("SOAPAction", "soap action url");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/xml;");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
int response = conn.getResponseCode();
Log.d(TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = convertInputStreamToString(is, length);
return contentAsString;
} finally {
if (is != null) {
is.close();
}
}
}
...
}
and I'm calling it using:
new DownloadTask().execute("asmx url");
how can I attach body to that HttpURLConnection ?
or if there's something more to do tell me.. I'm beginner at java
Try this
if(body != null) {
DataOutputStream writer = new DataOutputStream(conn.getOutputStream());
byte[] data = body.toString().getBytes("UTF-8");
writer.write(data);
writer.flush();
writer.close();
}
I have a following functionality: I create through the user form a new user. After i had submitted the entered data, created user get the bar-code, which would be used for get access to the other system section by scanning that bar-code with hand-scanner. So how can i get any value (in my case that bar-code from json calls (Post, Get, JSON) with Selenium WebDriver on Java?
Selenium has nothing to do with json. You can use Apache HttpClient library for sending GET, POST, PUT and DELETE requests and receiving the responses. Given below is a simplified function for all cases.
public static HttpResponse sendRequest(String requestType, String body,String url,
String... headers) throws Exception {
try {
HttpGet getRequest = null;
HttpPost postRequest;
HttpPut putRequest;
HttpDelete delRequest;
HttpResponse response = null;
HttpClient client = new DefaultHttpClient();
// Collecting Headers
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (String arg : headers) {
//Considering that you are applying header name and values in String format like this "Header1,Value1"
nvps.add(new BasicNameValuePair(arg.split(",")[0], arg
.split(",")[1]));
}
System.out.println("Total Headers Supplied " + nvps.size());
if (requestType.equalsIgnoreCase("GET")) {
getRequest = new HttpGet(url);
for (NameValuePair h : nvps) {
getRequest.addHeader(h.getName(), h.getValue());
}
response = client.execute(getRequest);
}
if (requestType.equalsIgnoreCase("POST")) {
postRequest = new HttpPost(url);
for (NameValuePair h : nvps) {
postRequest.addHeader(h.getName(), h.getValue());
}
StringEntity requestEntity = new StringEntity(body,"UTF-8");
postRequest.setEntity(requestEntity);
response = client.execute(postRequest);
}
if (requestType.equalsIgnoreCase("PUT")) {
putRequest = new HttpPut(url);
for (NameValuePair h : nvps) {
putRequest.addHeader(h.getName(), h.getValue());
}
StringEntity requestEntity = new StringEntity(body,"UTF-8");
putRequest.setEntity(requestEntity);
response = client.execute(putRequest);
}
if (requestType.equalsIgnoreCase("DELETE")) {
delRequest = new HttpDelete(url);
for (NameValuePair h : nvps) {
delRequest.addHeader(h.getName(), h.getValue());
}
response = client.execute(delRequest);
}
return response;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
Selenium only deals with browsers.
Java has classes that do http requests.
see the code below:
private HttpURLConnection setODataConnection(String url, String method) {
try {
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod(method);
// add request header
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json;odata=verbose");
return conn;
} catch (Exception e) {
Assert.fail(e.getMessage());
return null;
}
}
private StringBuilder sendODataRequest(HttpURLConnection conn) {
try {
int responseCode = conn.getResponseCode();
String method = conn.getRequestMethod();
System.out.println("\nSending '" + method + "' request to URL : " + conn.getURL());
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response;
} catch (Exception e) {
Assert.fail(e.getMessage());
return null;
}
}
private ArrayList<String> getByFullUrl(String fullUrl, String entity) {
HttpURLConnection conn = setODataConnection(fullUrl, "GET");
StringBuilder response = sendODataRequest(conn);
ArrayList<String> s = new ArrayList<String>();
Pattern p = Pattern.compile(entity + "\" : (.*?)\\}");
Matcher m = p.matcher(response);
while (m.find()) {
s.add(m.group(1).replace("\"", ""));
}
return s;
}
public ArrayList<String> get(String table, String entity) {
String url = oDataUrl + table + "?$select=" + entity;
return getByFullUrl(url, entity);
}
public void post(String table, String bodyDetails) {
String url = oDataUrl + table;
HttpURLConnection conn = setODataConnection(url, "POST");
conn.setDoOutput(true);
try {
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes("details={" + bodyDetails + "}");
wr.flush();
wr.close();
} catch (Exception e) {
Assert.fail(e.getMessage());
}
sendODataRequest(conn);
}
public void put(String table, String id, String bodyDetails) {
String url = oDataUrl + table + "(" + id + ")";
HttpURLConnection conn = setODataConnection(url, "PUT");
conn.setDoOutput(true);
try {
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes("details={" + bodyDetails + "}");
wr.flush();
wr.close();
} catch (Exception e) {
Assert.fail(e.getMessage());
}
sendODataRequest(conn);
}
I use the following Java code in a Bean to read a URL's content:
String url;
String inputLine;
StringBuilder srcCode=new StringBuilder();
public void setUrl (String value) {
url = value;
}
private void scanWebPage() throws IOException {
try {
URL dest = new URL(url);
URLConnection yc = dest.openConnection();
yc.setUseCaches(false);
BufferedReader in = new BufferedReader(new
InputStreamReader(yc.getInputStream()));
while ((inputLine = in.readLine()) != null)
srcCode = srcCode.append (inputLine);
in.close();
} catch (FileNotFoundException fne) {
srcCode.append("File Not Found") ;
}
}
The code works fine for most URL's, but does not work for redirected URLs. How can I update the above code to read content from redirected URLs? For redirected URLs, I get "File Not Found".
Give the following a go:
HttpURLConnection yc = (HttpURLConnection) dest.openConnection();
yc.setInstanceFollowRedirects( true );
In context to your code above:
`String url = "http://java.sun.com";
String inputLine;
StringBuilder srcCode=new StringBuilder();
URL dest = new URL(url);
HttpURLConnection yc = (HttpURLConnection) dest.openConnection();
yc.setInstanceFollowRedirects( true );
yc.setUseCaches(false);
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
while ((inputLine = in.readLine()) != null) {
srcCode = srcCode.append (inputLine);
}
in.close();`
Modified further to help you diagnose what is going on. This code turns off auto redirection and then manually follows the Location headers printing out as it goes along.
#Test
public void f() throws IOException {
String url = "http://java.sun.com";
fetchURL(url);
}
private HttpURLConnection fetchURL( String url ) throws IOException {
URL dest = new URL(url);
HttpURLConnection yc = (HttpURLConnection) dest.openConnection();
yc.setInstanceFollowRedirects( false );
yc.setUseCaches(false);
System.out.println( "url = " + url );
int responseCode = yc.getResponseCode();
if ( responseCode >= 300 && responseCode < 400 ) { // brute force check, far too wide
return fetchURL( yc.getHeaderField( "Location") );
}
System.out.println( "yc.getResponseCode() = " + yc.getResponseCode() );
return yc;
}
its not the debuggin of your prog , but you can consider this one
public class GetURLData
{
public static void main(String args[])
{
String url = "the url you want the response from";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
StringBuilder builder= new StringBuilder();
try
{
response = httpClient.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
char[] buf = new char[8000];
int l = 0;
while (l >= 0)
{
builder.append(buf, 0, l);
l = in.read(buf);
}
System.out.println(builder.toString);
} catch (Exception e)
{
System.out.println("Exception is :"+e);
e.printStackTrace();
}
}
}