如何在J2ME中为诺基亚Asha将Object转换为String?

时间:2014-07-08 17:57:36

标签: java string object java-me nokia-s40

我正在为诺基亚Asha开发并使用Tantalum库通过HTTPPoster类发出我的HTTP请求。

当执行任务时,我尝试从其余响应头中获取X-Session-Id头的值,这些值作为HashTable返回,此头中的值我需要将其转换为SHA256散列。

但是我无法将我从HashTable获得的值转换为String。

我的代码如下所示:

final HttpPoster httpPoster = new HttpPoster(Task.FASTLANE_PRIORITY, completeURL);
        httpPoster.setRequestProperty("Content-Type", "application/json");
        httpPoster.setPostData(new byte[]{});
        httpPoster.chain(new Task(Task.FASTLANE_PRIORITY){

            protected Object exec(Object in) throws CancellationException,
                    TimeoutException, InterruptedException {
                // TODO Auto-generated method stub
                System.out.println("Task is executing");

                String tmpSessionId = new String(httpPoster.getResponseHeaders().get("X-Session-Id").toString().getBytes());

                byte[] input = null;
                try {
                    input = new String("X-Session-Sig" + tmpSessionId + "test").getBytes("UTF-8");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    System.out.println("Unsupported encoding exception");
                    e.printStackTrace();
                }

                byte[] key = new byte[4];
                int tmpInt = new Random().nextInt();
                key[0] = (byte)(tmpInt >> 24);
                key[1] = (byte)(tmpInt >> 16);
                key[2] = (byte)(tmpInt >> 8);
                key[3] = (byte)(tmpInt);


                Digest digest = new SHA256Digest();
                HMac hmac = new HMac(digest);
                hmac.init(new KeyParameter(key));
                hmac.update(input, 0, input.length);
                byte[] output = new byte[digest.getDigestSize()];
                hmac.doFinal(output, 0);
                sessionId = tmpSessionId;
                sessionSig = new String(Hex.encode(output));
                System.out.println("session id " + sessionId + " session signature " + sessionSig);
                return in;
            }
            protected void onCanceled(){
                System.out.println("Request was cancelled");
            }
        });
        httpPoster.fork();

如您所见,在行String tmpSessionId = new String(httpPoster.getResponseHeaders().get("X-Session-Id").toString().getBytes());中我尝试转换为String然后获取字节,但这会返回 [Ljava.lang.String; @ 6f7159d ,而不是实际我正在寻找的值,即使在不执行getBytes方法的情况下调用方法 toString()也会返回相同的值。

如何在HashTable中获取此元素的真实值?据我所知,J2ME不支持ObjectOutputStream类。有哪些替代方案?

1 个答案:

答案 0 :(得分:0)

我发现 [Ljava.lang.String; @ 6f7159d 部分意味着HashTable中的对象是一个String数组。

意识到我只需要转换为String []:

String[] stringArray = (String[]) dotREZApi.getCurrentRequest().getResponseHeaders().get("X-Session-Id");
String tmpSessionId = stringArray[0];

这让我觉得我期待的价值。