I am trying to make a request via HttpURLConnection which is then handled by a certain struts Action. I construct name-value pairs for request URL by iterating through provided request parameters. The problem is that original request contains some parameters written in Cyrillic and after new request is sent out, in the struts Action responsible for handling this request, i get garbage(question marks, squares etc.) instead of parameters written in Cyrillic.
Note:Encoding parameters for the new URL with UTF-8 does not have any result. Parameters written in cyrillic are displayed correctly in the scope of this method.
Did anybody encounter similar problem and if so, how did you solve it?
Thanks in advance.
Here is the code:
Expand|Select|Wrap|Line Numbers
- private Map params = new HashMap(); // This map is filled out with HttpServletRequest.getParameterMap()
- public InputStream read() throws IOException {
- log.debug("Trying to read data from url [" + resource.toString() + "]");
- URL requestUrl = resource;
- /*open new URLConnection*/
- HttpURLConnection httpCon = (HttpURLConnection) requestUrl.openConnection();
- httpCon.setDoOutput(true);
- httpCon.setDoInput(true);
- httpCon.setUseCaches(false);
- httpCon.setRequestMethod("POST");
- /*add headers*/
- for (Iterator e = headers.keySet().iterator(); e.hasNext();) {
- String headName = e.next().toString();
- String headValue = (String)headers.get(headName);
- httpCon.setRequestProperty(headName, headValue);
- System.out.println("Setting: " + headName + " --- " + headValue);
- }
- /*add parameters*/
- httpCon.connect();
- log.debug("Connect successful");
- StringBuffer buffer = new StringBuffer();
- log.debug("----------------Map parameters--------------------");
- for (Iterator i = params.keySet().iterator(); i.hasNext(); ) {
- String key = (String) i.next();
- log.debug("name=" + key);
- Object value = params.get(key);
- if (value instanceof String[]){
- String [] arrVal = (String[]) value;
- for (int j = 0; j < arrVal.length; j++){
- log.debug("value=" + arrVal[j]);
- buffer.append(key + "=" + arrVal[j] + ((j+1 < arrVal.length || i.hasNext()) ? "&" : ""));
- log.debug("valueEncoded=" + encodeURL(arrVal[j], "UTF-8"));
- }
- }else{
- log.debug("value=" + value);
- buffer.append(key + "=" + value + (i.hasNext() ? "&" : ""));
- }
- }
- log.debug("----------------Map parameters--------------------");
- /* Send request parameters */
- PrintWriter out = new PrintWriter(httpCon.getOutputStream());
- out.write(buffer.toString());
- out.flush();
- out.close();
- /* make request */
- int responseCode = httpCon.getResponseCode();
- log.debug("Response code: " + responseCode);
- if (responseCode != 200)
- throw new IOException("Invalid HTTP response code. Response code: " + responseCode + ". Message: " + getContentFromInputStream(httpCon.getErrorStream()));
- return httpCon.getInputStream();
- }