无法使用Java

时间:2019-02-19 10:57:48

标签: java web-services

我们正在使用Java代码执行Web服务。 Web服务响应来自Web服务提供商,格式为gzip。收到响应后,我们将使用GZIPInputStream解压缩响应。

响应被转换为字节码,然后作为输入传递给gzipinputstream。该代码在Eclipse中运行良好,并且能够解压缩响应字符串。相同的代码在Linux中不起作用,并且在将字节数组传递给gzipinputstream时抛出错误“ Not in Gzip format”。

我们检查了Windows中默认的字符集为Windows-1252,而Linux中的默认字符集为UTF-8。因此,我们尝试获取UTF-8和Windows-1252中的字节。两者都不起作用。

任何人都可以帮助我哪里出了问题以及如何解决该问题?

试图在生成响应的字节码时更改字符集。

import java.util.List;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URL;
import java.io. * ;
import java.nio.charset.*;
import java.util.zip.GZIPInputStream;
import java.nio.charset.*;

public class WSConnectTest {

    public final static String UserName = null; //User id login for Fusion
    public final static String instanceURL = null;
    public final static String USER_PWD = null; // API key shared by CSOD

    private static final String PROXY_URL = null; //UBS proxy URL
    private static final int PROXY_PORT = 8080;
    private static final String PROXY_USERNAME = "USER_NAME";
    private static final String PROXY_PASSWORD = "PASSWORD";
    final static String USER_AGENT = "Mozilla/5.0";

    static Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
    PROXY_URL, PROXY_PORT));

    static {
        Authenticator authenticator = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return (new PasswordAuthentication(UserName, USER_PWD.toCharArray()));
            }
        };
        Authenticator.setDefault(authenticator);

    }

    public static void main(String[] args) throws Exception {

        FusionConnect fusionconnect = new FusionConnect();

        String theURL = instanceURL + "<RESOURCE_NAME>";
        System.out.println("The URL to be called is : " + theURL);
        String json = "<JSON_STRING>"
        String post_param = new String(json.toString());
        System.out.println("The json is :" + json);

        PostRequestWithFilter(theURL, post_param);

    }

    private static void PostRequestWithFilter(String url, String json) throws Exception {

        try {

            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection(proxy);

            con.setRequestMethod("POST");

            con.setRequestProperty("User-Agent", "Apache-HttpClient/4.1.1 (java 1.5)");
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Accept-Language", "UTF-8");
            con.setRequestProperty("Accept-Encoding", "gzip, deflate");
            con.setDoOutput(true);

            con.setConnectTimeout(15000);

            System.out.println("get content type :"+con.getRequestProperties());

            DataOutputStream wr = new DataOutputStream(con.getOutputStream());

            wr.writeBytes(json);
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("\nResponse Code : " + responseCode);
            System.out.println("\nResponse message : " + con.getResponseMessage());

            String inputLine;
            StringBuffer response = new StringBuffer();
            String ResponseStr = null;
            byte[] bresponse = new byte[1024];
            String deoutput = null;
            BufferedReader in =null;
            if (responseCode == con.HTTP_CREATED) { in =new BufferedReader(new InputStreamReader(con.getInputStream()));

                                while ((inputLine = in.readLine()) != null) {
                                        response.append(inputLine);
                                        System.out.println("Response received from Fusion string buffer :"+inputLine);
                                } in .close();

                                ResponseStr = response.toString();
                                System.out.println("response string :"+ResponseStr);
                                bresponse = ResponseStr.getBytes("UTF-8");
                                System.out.println("Response received from Fusion Bytes :"+bresponse);
                                deoutput = unzip(bresponse);
                                System.out.println("Decompressed response :"+deoutput);
            } else { in =new BufferedReader(new InputStreamReader(con.getErrorStream()));

                System.out.println("Response Content Type :"+con.getContentType());
                System.out.println("Response Content Encoding :"+con.getContentEncoding());

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine+"\r");
                    System.out.println("Response received from Fusion string buffer :"+inputLine);
                } 
                in .close();

                ResponseStr = response.toString();
                System.out.println("response string :"+response);
                bresponse = ResponseStr.getBytes();

                for (int i=0; i < bresponse.length; i++)
                {
                 System.out.println("byte code :"+i+" "+bresponse[i]);
                }           

                System.out.println("Response received from Fusion Bytes :"+Charset.defaultCharset()+bresponse);
                deoutput = unzip(bresponse);
                FileOutputStream fos = new FileOutputStream("fileName1.gz");
                DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
                outStream.writeUTF(ResponseStr);
                outStream.close();

                System.out.println("Decompressed response :"+deoutput);
            } 
        }
        catch(Exception e) {
            e.printStackTrace();

        }

    }
    public static String unzip(byte[] compressed) {
        if ((compressed == null) || (compressed.length == 0)) {
            System.out.println("The response is empty");
            throw new IllegalArgumentException("Cannot unzip null or empty bytes");
        }
        if (!isZipped(compressed)) {
            System.out.println("The response is not zipped");
            return new String(compressed);
        }

        StringBuilder output = new StringBuilder();
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressed)) {
                    System.out.println("After byte array input stream :");
            try (GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream)) {
                try (InputStreamReader inputStreamReader = new InputStreamReader(byteArrayInputStream, StandardCharsets.UTF_8)){
                    try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
                        String line;
                        System.out.println("buffer reader :"+bufferedReader.readLine());
                        while ((line = bufferedReader.readLine()) != null) {
                            output.append(line);
                            System.out.println("line :"+output.toString());
                        }
                    } catch(IOException e) {
                        throw new RuntimeException("Failed to read bufferedReader content", e);
                        }
                }
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
        return output.toString();
    }
    public static boolean isZipped(final byte[] compressed) {
        System.out.println("(byte)(GZIPInputStream.GZIP_MAGIC) is "+(byte)(GZIPInputStream.GZIP_MAGIC));
        System.out.println("gzip magic is "+(byte)(GZIPInputStream.GZIP_MAGIC >> 8));
        return (compressed[0] == (byte)(GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte)(GZIPInputStream.GZIP_MAGIC >> 8));
    }
}

0 个答案:

没有答案