I am using HttpUrlConnection to post a query to a webpage. The web page take my request and does another posting. For example: www.unknown.com
URL url = new URL("http://www.unknown.com"); //$NON-NLS-1$
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(15*1000);
urlConnection.setDoInput(true);
urlConnection.setDoOutput (true);
urlConnection.setUseCaches (false);
urlConnection.setAllowUserInteraction(true);
out = new OutputStreamWriter(urlConnection.getOutputStream());
string content = "var1=5&var2=0&var3=6"; //$NON-NLS-1$
out.write(content);
out.flush();
out.close();
The code is working without problem and I am getting the html code. The problem is that the webpage is proceeding another HTTP "POST" method when it is taking my request. For example after my request the URI is: http://www.unknown.com?var1=5&var2=0&var3=6&var4=1500
I need to get the value of "var4" in my code and I can not find any soluti开发者_如何学Goon for this. HttpUrlConnection.getUrl() returns just the address http://www.unknown.com! Have anybody a suggestion? Thanks.
How about using "getQuery()" to retrieve the Query String.
String query = url.getQuery();
This will give you the the query part of this URL.
Use StringTokenizer to separate the parameters. (You will have to apply StringTokenizer twice.)
First get tokens from query string which are separated by "&". This will return "val1=5" , "val4=1500", etc.
To the above tokens apply StrinTokenizer once again. This time retrieve tokens separated by the "=". Now iterate through this, the first token will be the parameter name "val4", the second token will be the value "1500".
StringTokenizer st = new StringTokenizer(query,"&",false); //query is from getQuery()
while (st.hasMoreElements())
{ // First Pass to retrive the "parametername=value" combo
String paramValueToken = st.nextElement().toString();
StringTokenizer stParamVal = new StringTokenizer(paramValueToken, "=", false );
int i = 0;
while (stParamVal.hasMoreElements())
{
//Second pass to separate the "paramname" and "value".
// 1st token is param name
// 2nd token is param value
String separatedToken = stParamVal.nextElement().toString();
if( i== 0)
{
//This indicates that it is the param name : ex val4,val5 etc
String paramName = separatedToken;
}
else
{
// This will hold value of the parameter
String paramValue = separatedToken;
}
i++;
}
}
URL getQuery() API Documentation
http://download.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html
精彩评论