Android使用BASE64编码后使用HTTPPOST将数据发布到服务器

时间:2013-08-12 07:29:01

标签: android web

我正在尝试使用HTTPPOST向服务器发送数据。我使用BASE64.encodetoString()编码了用户名和密码。但我无法发布数据。没有错误,但每次都会收到 400或404响应代码。在Java中完成代码时成功执行,但它在android中没有按预期工作。请帮帮我。

以下是我正在使用的代码:

public void  getLoginInfo()
{
   String user="xxxx@gmail.com";
   String password="1234xyz";

     // Creating HTTP client
       HttpClient httpClient = new DefaultHttpClient();
        // Creating HTTP Post
        HttpPost httpPost = new HttpPost(url);

       // String base64EncodedCredentials = "Basic " + Base64.encodeToString((user + ":" + password).getBytes(),0);
        // Building post parameters
        // key and value pair

        byte[] data=(user+":"+password).getBytes();
        String base64EncodedCredentials =Base64.encodeToString(data, Base64.DEFAULT);
        String httpheader="Basic "+base64EncodedCredentials;
        System.out.println("httpheader "+httpheader);
       /* List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
        nameValuePair.add(new BasicNameValuePair("email", "nishanth.s@giwitservices.com"));
        nameValuePair.add(new BasicNameValuePair("password","100006438166763hbsV1v0"));*/
        // Url Encoding the POST parameters


        // Making HTTP Request
      //  try {
            try {
                httpPost.setHeader("Authorization", httpheader);
                //httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
                HttpResponse response = httpClient.execute(httpPost);
                 System.out.println("response test "+response.toString());
                 System.out.println("response code "+response.getStatusLine().getStatusCode());
                 String the_string_response = convertResponseToString(response);
                 System.out.println("respones "+the_string_response);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                       
}

3 个答案:

答案 0 :(得分:2)

不要使用BASE64.DEFAULT,而是尝试使用BASE64.NO_WRAP。这将有助于您解决问题。

答案 1 :(得分:1)

改变这个:

String base64EncodedCredentials =Base64.encodeToString(data, Base64.DEFAULT);

对此:

String base64EncodedCredentials =Base64.encodeToString(data, Base64.NO_WRAP|Base64.URL_SAFE);

希望这有帮助。

答案 2 :(得分:0)

你为什么不用这个:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("key_of_data", data));            

HttpPost oHttpPost = new HttpPost(your_url);
oHttpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

而不是使用 Base64 编码