使用HttpURLConnection发布数据

时间:2014-01-03 15:46:16

标签: java servlets http-post httpconnection

我需要使用HttpURLConnection将数据发布到服务器。数据也包含泰语字符。接受邮件请求的服务器接受编码UTF-8和TIS-620。当我直接从其他客户端发布数据时,它运行正常,但是当我从java代码发送相同的请求时,它无法正常工作,我的意思是当我发送UTF-8格式数据时,它会提供解析异常,当我使用TIS-620代替泰语时服务器中的文字我得到一些特殊的字符平方等(我没有任何接受数据的服务器上的句柄)

我为HttpURLConnection设置了相同的标题属性,我在浏览器中设置了休息客户端。请告诉我这里可能出现的问题

根据我的要求,我必须在servlet中编写这段代码,并从浏览器AJAX调用中调用servlet。在发送数据的JQUERY AJAX调用中我正在设置

beforeSend: function(xhr) {
                    xhr.setRequestHeader( "Content-type", "application/json; charset=UTF-8" );
                },

我将UTF-8改为TIS-620所有地方但没有运气

一些发现:

我订的时候     connection.setRequestProperty(“Content-Type”,“application / json; charset = UTF-8”); 并打印connection.getContentType()它只打印 application / json

如果我只发送英文文本,它可以正常工作。我在下面提供servlet代码,接受post请求并将其POST到服务器

protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        System.err.println("************** POST CALLED **************");

        //PRINT SERVLET REQUEST PROPERTY
        System.err.println("CharacterEncoding : "+ request.getCharacterEncoding());
        System.err.println("ContentType : "+request.getContentType());

        //SEND GET REQUEST AND FETCH XCSRF TOKEN
        String dummyServiceUrl = "GET_LOT_SRV/get_lot";
        String xcsrfToken = null;
        HttpURLConnection connection = null;
        String requestURL = httpPrefix + hostName + semiColon + portNumber + forwardSlash + dummyServiceUrl;
        List<String> cookies = null;
        try {
            URL gatewayServiceUrl = new URL(requestURL);
            connection = (HttpURLConnection) gatewayServiceUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Authorization", this.getBasicAuth());
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("x-csrf-token", "fetch");
            connection.connect();
            if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                //ON SUCCESS GET XCSRF TOKEN AND IN SAME SESSION POST DATA 
                requestURL = httpPrefix + hostName + semiColon + portNumber + forwardSlash + request.getQueryString();
                gatewayServiceUrl = new URL(requestURL);
                connection = (HttpURLConnection) gatewayServiceUrl.openConnection();

                //SET CONNECTION PROPERTY
                connection.setRequestMethod("POST");
                xcsrfToken = connection.getHeaderField("x-csrf-token");
                cookies = connection.getHeaderFields().get("set-cookie");
                // SET COOKIES
                for (String cookie : cookies) {
                    String tmp = cookie.split(";", 2)[0];
                    connection.addRequestProperty("Cookie", tmp);
                }
                //SET HEADERS
                connection.setRequestProperty("Authorization", this.getBasicAuth());
                connection.setRequestProperty("x-csrf-token", xcsrfToken);
                connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
                connection.setRequestProperty("Accept", "application/json");
                connection.setRequestProperty("DataServiceVersion", "2.0");
                connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
                connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
                connection.setRequestProperty("Accept-Charset", "UTF-8"); 

                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setUseCaches(false);

                //SET USERS INPUT DATA TO OUTPUT STREAM
                String payload = this.getDataFromStreamPost(request.getInputStream());
                DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
                dataOutputStream.write(payload.getBytes());
                dataOutputStream.flush();
                dataOutputStream.close();

                //POST DATA AND CHECK RESPONSE
                connection.connect();
                response.setStatus(HttpURLConnection.HTTP_CREATED);
                response.setContentType("application/json; charset=TIS-620");
                response.getWriter().println(this.getDataFromStream(connection.getInputStream()));

            } else {
                System.err.println("XCSRF GET FAILURE "+connection.getResponseCode());
                response.setStatus(connection.getResponseCode());
                response.setContentType("application/json; charset=TIS-620");
                response.getWriter().println(this.getDataFromStream(connection.getInputStream()));
            }
        } catch (Exception e) {
            System.err.println("EXCEPTION OCCURED IN POST : "+e.getMessage());
            response.setStatus(connection.getResponseCode());
            response.setContentType("application/json; charset=TIS-620");
            response.getWriter().println(this.getDataFromStream(connection.getErrorStream()));
        }
    }
        private String getBasicAuth() {
        String userpass = userName + ":" + password;
        return "Basic "
                + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass
                        .getBytes());
    }

    private String getDataFromStream(InputStream stream) throws IOException {
        StringBuffer dataBuffer = new StringBuffer();
        BufferedReader inStream = new BufferedReader(new InputStreamReader(
                stream));
        String data = "";

        while ((data = inStream.readLine()) != null) {
            dataBuffer.append(data);
        }
        inStream.close();

        return dataBuffer.toString();
    }
    private String getDataFromStreamPost(InputStream stream) throws IOException {
        StringBuffer dataBuffer = new StringBuffer();
        BufferedReader inStream = new BufferedReader(new InputStreamReader(
                stream,"UTF-8"));
        String data = "";

        while ((data = inStream.readLine()) != null) {
            dataBuffer.append(data);
        }
        inStream.close();

        return dataBuffer.toString();
    }

0 个答案:

没有答案