java - The "inverse" method of getParameter() -
one way of sending user parameters appending them url:
urladdress+="?param1=value1+param2=value2"
how else can send user parameters server? these params read httpservletrequest method
getparameter(param1);
on receiver's end.
i tried
setrequestproperty("param1","value1");
of httpurlconnection. however, getparameter() couldn't find them on request.
i trying send them outside th url won`t visible.
you have 2 possibilities: either append them url in case of request, visible, or write them body in case of post request:
/** * convert map query string. * @param values map values * <code>null</code> encoded empty string, other * objects converted * string calling <code>tostring()</code> method. * @return e.g. "key1=value&key2=&email=max%40example.com" */ public static string querystring(map<string, object> values) { stringbuilder sbuf = new stringbuilder(); string separator = ""; (map.entry<string, object> entry : values.entryset()) { string value = entry.getvalue() == null ? "" : string.valueof(entry.getvalue()); sbuf.append(separator); sbuf.append(urlencode(entry.getkey())); sbuf.append('='); sbuf.append(urlencode(value)); separator = "&"; } return sbuf.tostring(); } static string urlencode(string value) { try { return urlencoder.encode(value, "utf-8"); } catch (unsupportedencodingexception e) { return value; } }
in case of post, have set header content-type
application/x-www-form-urlencoded
. recommend using 'utf-8' encoding. if not appropriate you, have dig how handle different encodings.
so instead of
http://www.example.com/path/resource?abc=124&xyz=john+doe
you write body:
abc=124&xyz=john+doe
setting parameters headers (addrequestheader()
) should not done, since middleware (e.g. web application firewall, proxy, load-balancer) parse headers , conflict pre-defined headers.
the above code taken davidwebb. there can see list of libraries can ease life when have deal http requests , don't want use httpurlconnection
natively.
why did add code building query string?
you can read many questions here on mistake didn't encode parameter names or values correctly.
Comments
Post a Comment