I have one request which response is displayed as url below. I need to extract user_token value from url and pass to subsequent request.
response url: http://example.com?user_token=0c1c59bc-3aaa-40f1-b978-7172de09a27f&m_id=9999&code=200&is_register=false&M=SUCCESS
i want to extract user_token from it and want to pass it to subsequent request, need solution in java code not java script.
You can do this:
String getTokenId(String url){
String[] splitUrl = url.split("user_token=");
String tokenId = "";
if(splitUrl.length >1){
for(int i =0; i < splitUrl[1].length(); i++){
if(splitUrl[1].charAt(i) == '&'){
tokenId = splitUrl[1].substring(0,i);
break;
}
}
}
return tokenId;
}
But if you know the exact length of the token, it could be a search.
Maybe what you need is request.getParameter("user_token"). You can do this in servlet for example
Related
How can I get the value "2" of "entityId=2" from this example Url: https://test.com/form/form.htm?Index=0&entityId=2&wid=74&_wid=74 using Java and assuming this value is not static?
I am using:
URL url = new URL("https://test.com/form/form.htm?Index=0&entityId=2&wid=74&_wid=74");
String quesries = url.getQuery();
int i = quesries.length();`enter code here`
System.out.println(i);
Which gave me length of 33.
You just have to use the substring method in Java.
String entityId = urlString.substring(urlString.indexOf("entityId=")+9,urlString.indexOf("&wid"))
Let's say I have a page which lists things and has various filters for that list in a sidebar. As an example, consider this page on ebuyer.com, which looks like this:
Those filters on the left are controlled by query string parameters, and the link to remove one of those filters contains the URL of the current page but without that one query string parameter in it.
Is there a way in JSP of easily constructing that "remove" link? I.e., is there a quick way to reproduce the current URL, but with a single query string parameter removed, or do I have to manually rebuild the URL by reading the query string parameters, adding them to the base URL, and skipping the one that I want to leave out?
My current plan is to make something like the following method available as a custom EL function:
public String removeQueryStringParameter(
HttpServletRequest request,
String paramName,
String paramValue) throws UnsupportedEncodingException {
StringBuilder url = new StringBuilder(request.getRequestURI());
boolean first = true;
for (Map.Entry<String, String[]> param : request.getParameterMap().entrySet()) {
String key = param.getKey();
String encodedKey = URLEncoder.encode(key, "UTF-8");
for (String value : param.getValue()) {
if (key.equals(paramName) && value.equals(paramValue)) {
continue;
}
if (first) {
url.append('?');
first = false;
} else {
url.append('&');
}
url.append(encodedKey);
url.append('=');
url.append(URLEncoder.encode(value, "UTF-8"));
}
}
return url.toString();
}
But is there a better way?
The better way is to use UrlEncodedQueryString.
UrlEncodedQueryString can be used to set, append or remove parameters
from a query string:
URI uri = new URI("/forum/article.jsp?id=2¶=4");
UrlEncodedQueryString queryString = UrlEncodedQueryString.parse(uri);
queryString.set("id", 3);
queryString.remove("para");
System.out.println(queryString);
I'm trying to get param values passed to a Java Servlet but the string returned is not correct. I'm storing the values in a Map and checking if the key exists.
Map params;
params = request.getParameterMap();
String id = params.get("id").toString();
String data = params.get("data").toString();
System.out.println("streaming" + data + " with id of " + id);
Yet if I call this servlet via http://localhost:8080/Serv/stream/data?data=hereisdata&id=you my output looks like this:
streaming[Ljava.lang.String;#5e2091d3 with id of [Ljava.lang.String;#36314ab8
What am I missing?
EDIT: as the suggested answers are not working, I'm including the entire class as I'm likely messing something up within the class:
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import Engine.Streamer;
public class AnalyzerController {
private Map params;
private String pathInfo;
private HttpServletRequest request;
public AnalyzerController(HttpServletRequest request)
{
this.params = request.getParameterMap();
this.pathInfo = request.getPathInfo();
}
public void processRequest()
{
System.out.println("procing with " + pathInfo);
switch(pathInfo){
case "/stream/data":
if(params.containsKey("id") && params.containsKey("data")) processStream();
break;
}
}
private void processStream()
{
System.out.println("we are told to stream");
String data = request.getParameter("data");
String id = request.getParameter("id");
Streamer stream = new Streamer();
stream.streamInput(data, "Analyzer", id);
}
}
This line specifically is throwing the NPE: String data = request.getParameter("data");
If you look at the docs of the Request#getParameterMap(), it returns a Map of the type Map<String, String[]>. Therefore, you need to take out the first element from the value String[] array returned from the map.
String id = params.get("id")[0];
Ofcourse, you can avoid all this and directly get the parameters from the request objects using the Request#getParameter() method.
String id = request.getParameter("id");
Edit: Looking at your class code, it seems that the instance variable request is not initialized. Initialize that in the constructor like this:
public AnalyzerController(HttpServletRequest request)
{
this.request = request; // Initialize your instance variable request which is used in the other methods.
this.params = request.getParameterMap();
this.pathInfo = request.getPathInfo();
}
You can get the required parameters instead of the whole map
String id = request.getParameter("id");
String data = request.getParameter("data");
Try something like this.
String data = ((String)params.get("data"));
Or directly from the Request.
String data = request.getParameter("data");
You can use request object plus it's method for to get data usinggetParameter() of you can use getParameterValues() if multiple data are from page.
String id = request.getParameter("id")
String data = request.getParameter("data")
why are you using Map ?
Any special need of it or any reason ?
or you can use like this :
String id = params.get("id")[0];
I have capture the current URL on the page.
using :
String url = driver.getCurrentUrl();
Now I want a specific text inside this string. Let say
String url = http://www.youtube.com/watch?v=R5-gtsdenpE
and I want
Capture and store the current page URL in String URL. (Done)
Capture the text in the URL after "v" and store it in String emb. (??)
I am using JAVA to write my scripts on Ubuntu.
Use:
String fullURL = http://www.youtube.com/watch?v=R5-gtsdenpE;
String emb = fullURL.split("\\?v=")[1];
This is what you want I guess-
String string = "http://www.youtube.com/watch?v=R5-gtsdenpE";
URL url = new URL(string);
System.out.println(url.getQuery());
Handle the exception appropriately.
In case you don't want to use URL class, just search for the first index of ? and then use substring() to get the string after that.
System.out.println(string.substring(string.indexOf("?")+1));
Url url = new Url(driver.getCurrentUrl());
Map<String, String[]> params = parameterMapFromString(url.getQuery());
String v = params.get("v")[0];
If you are requirement is static and you are sure that you have to get the value after "v" than you can try this also
String emb = url.substring(url.indexOf("v"), url.length()).trim();
I have this on my webservice:
function listar($username)
{
$result = mysql_query("SELECT Name FROM APKs WHERE Tipo=0");
//$registo = mysql_fetch_array($result);
$numero = 0;
while($registo = mysql_fetch_array($result))
{
$regs[$numero] = $registo['Name'];
$numero++;
}
return $regs;
//return mysql_fetch_array($result);
}
in Java, after the SOAP call (not relevant now) I read it this way:
Object response = envelope.getResponse();
String x = response.toString();
I need to access which one of those fields (selected from the database) so I thought, why not split the array into strings?
I tried two methods:
String[] arr=x.split(" ");
System.out.println("Array :"+arr.length);
for(int i=0;i<arr.length;i++)
{
..
}
StringTokenizer stArr=new StringTokenizer(x," ");
while(stArr.hasMoreTokens())
{
...
}
But none of them worked, whick make me believe I'm returning badly the array in first place.
Any help?
UPDATE:
So I'm using again xsd:string;
Now I have on my webservice return json_encode($regs);
To convert the object from the response I'm using a specific google api
http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
Object response = envelope.getResponse();
Gson gson = new Gson();
String jstring = gson.toJson(response);
But I'm with difficulty parsing the "jstring" because it's format: "[\"SOMETHING\",\"SOMETHING\",\"SOMETHING\",\"SOMETHING\",.....]". I have not any identifier to get those values.
How can I extract those dynamic values and assign them to String[]?
USE:
json_encode($array); in PHP
and
JSONObject in Java to read.
See this example: http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
UPDATE
Change the line:
$regs[$numero] = $registo['Name'];
to:
$regs[] = array('name' => $registo["name"]);
If you need to get the ID, you also can do:
$regs[] = array('name' => $registo["name"], 'id' => $registo["id"]);
FORGET:
The mysql_fetch_array returns a real array not a string. It's not needed to split a string.
Be sure that your PHP Web Service is returning a xsd:array
Generate a new proxy using some generator like http://www.soapui.org. Just use the proxy. Nothing else.
Try to use JSON and you can esy build easy object and read it.