One way of sending the user parameters is appending them to the URL:

URLAddress+="?param1=value1+param2=value2"

How else can i send user parameters to the server? These are the params to be read by the HttpServletRequest method

getParameter(param1);

on the receiver's end.

I tried

setRequestProperty("param1","value1"); 

of HttpURLConnection. However, getParameter() couldn't find them on the request.

I am trying to send them outside th URL so that they won`t be visible.

有帮助吗?

解决方案

You have only two possibilities: Either append them to the URL in case of GET request, then they are visible, or write them as the body in case of POST request:

/**
 * Convert a Map to a query string.
 * @param values the map with the values
 *               <code>null</code> will be encoded as empty string, all other
 *               objects are converted to
 *               String by calling its <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 = "";

    for (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, you have to set the header Content-Type to application/x-www-form-urlencoded. I recommend using 'UTF-8' as encoding. If this is not appropriate for you, you have to dig how to handle different encodings.

So instead of

http://www.example.com/path/resource?abc=124&xyz=John+Doe

you write the body:

abc=124&xyz=John+Doe

Setting parameters as headers (addRequestHeader()) should not be done, since most middleware (e.g. web application firewall, proxy, load-balancer) parse the headers and you could conflict with pre-defined headers.

The above code is taken from DavidWebb. There you can see a list of libraries which can ease your life when you have to deal with HTTP requests and don't want to use HttpURLConnection natively.

Why did I add the code for building a query string?

You can read many questions here on SO where the mistake was that they didn't encode parameter names or values correctly.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top