开发者

Android HttpRequest issue

Hi I'm using HttpPost and HttpRequest to connect to a server and get the result. I get the result as string and trying to convert it in byte[]. But when I do that the result which I'm getting as String and byte[] is different. How can I fix that? Here is the code I'm using :

public class TestProjectActivity extends Activity {

    Button cancel,login;
    HttpClient httpclient;
    HttpPost httppost;
    ArrayList<NameValuePair> postParameters;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        httpclient = new DefaultHttpClient();
        httppost = new HttpPost("http://www.rpc.example.com");

        postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("username_hash", "c34a6cf6bff9f6b61e96fdf4bf360157d522a17c"));
        postParameters.add(new BasicNameValuePair("password_hash", "56dc55f0062cf21797637b0f8652293023f2ef22"));

        cancel = (Button) findViewById(R.id.cancel_login_btn);
        cancel.setOnClickListener(new View.OnClickListener() {

            @Override
 开发者_Python百科           public void onClick(View v) {
                finish();
            }
        });

        login = (Button) findViewById(R.id.login_btn);
        login.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                try {
                    httppost.setEntity(new UrlEncodedFormEntity(postParameters));

                    HttpResponse response = httpclient.execute(httppost);
                    String responseBody = EntityUtils.toString(response.getEntity()); //response
                    byte[] b = responseBody.getBytes();
                    Log.e("Packet","Response packet : "+b); //print packet
                    Log.e("Packet","Response packet : "+responseBody); //print packet





                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d("ERROR"," Error lol - "+e);
                }

            }
        });
    }
}

The result as string is : Response packet : 00000000000000000000000000000001002001ec8ce6abb3e952a85b8551ba726a122700000000000000000000000000000002000000000000000000000000000001162c1c0624f7a2b272e05c4d997473a8e6001eyJsb2NhbGUiOiJlbl9VUyIsImlkIjoyLCJlcnJvcl9jb2RlIjo2MDAzLCJlcnJvcl9zdHJpbmciOiJVbnN1cHBvcnRlZCBDbGllbnQgVmVyc2lvbiJ9

The result as byte[] is : Response packet : [B@462d93c0


byte[].toString() always prints "[B@...".

Use Log.e("Packet","Response packet : "+ new String(b, "UTF-8")); //print packet

This will create a new String from you byte[] (which you don't really need to do, since you have it already from the other method you are calling).


You'll need to set the correct encoding of the response String, for example:

byte[] b = responseBody.getBytes("UTF-8");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜