使用http post params android进行基本身份验证

时间:2013-07-31 13:18:22

标签: android http-post basic-authentication

我正在通过传递用户名和密码进行基本身份验证,然后使用BasicNameValuePair发送post params以获取服务的响应。

我的方法:

public StringBuilder callServiceHttpPost(String userName, String password, String type)
    {

        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(WEBSERVICE + type);



        HttpResponse response = null;

        StringBuilder total = new StringBuilder();

        try {

            URL url = new URL(WEBSERVICE + type);

            /*String base64EncodedCredentials = Base64.encodeToString((userName
                    + ":" + password).getBytes(), Base64.URL_SAFE
                    | Base64.NO_WRAP);*/

            String base64EncodedCredentials = "Basic " + Base64.encodeToString(
                    (userName + ":" + password).getBytes(),
                    Base64.NO_WRAP);


            httppost.setHeader("Authorization", base64EncodedCredentials);

            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
            nameValuePairs.add(new BasicNameValuePair("day", Integer.toString(2)));
            nameValuePairs.add(new BasicNameValuePair("emailId", "usertest@gmail.com"));
            nameValuePairs.add(new BasicNameValuePair("month", Integer.toString(5)));
            nameValuePairs.add(new BasicNameValuePair("year", Integer.toString(2013)));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            response = httpclient.execute(httppost);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            try {
                InputStream instream = entity.getContent();

                String line = "";


                // Wrap a BufferedReader around the InputStream
                BufferedReader rd = new BufferedReader(new InputStreamReader(instream));

                // Read response until the end
                while ((line = rd.readLine()) != null) { 
                    total.append(line); 
                }

            } catch (IllegalStateException e) {

                e.printStackTrace();
            } catch (IOException e) {

                e.printStackTrace();
            }
        }


        return total;
    }

但我总是得到这个:

 <html><head>   <title>Status page</title></head><body><h3>Invalid json representation of content</h3><p>You can get technical details <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1">here</a>.<br>Please continue your visit at our <a href="/">home page</a>.</p></body></html>

3 个答案:

答案 0 :(得分:5)

这是怎么做的:

public String callServiceHttpPost(String userName, String password, String type)
    {

        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(WEBSERVICE + type);

            String responseBody = "";

        HttpResponse response = null;

        try {

            String base64EncodedCredentials = "Basic " + Base64.encodeToString( 
                    (userName + ":" + password).getBytes(), 
                    Base64.NO_WRAP);


            httppost.setHeader("Authorization", base64EncodedCredentials);

            httppost.setHeader(HTTP.CONTENT_TYPE,"application/json");

            JSONObject obj = new JSONObject();

            obj.put("day", String.valueOf(2)); 
            obj.put("emailId", "userTest@gmail.com");
            obj.put("month", String.valueOf(5));
            obj.put("year", String.valueOf(2013));


             httppost.setEntity(new StringEntity(obj.toString(), "UTF-8"));

            // Execute HTTP Post Request
            response = httpclient.execute(httppost);

            if (response.getStatusLine().getStatusCode() == 200) {
                 Log.d("response ok", "ok response :/");
            } else {
                Log.d("response not ok", "Something went wrong :/");
            }

            responseBody = EntityUtils.toString(response.getEntity());

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        catch (JSONException e) {
            e.printStackTrace();
        }

        return responseBody;
    }

答案 1 :(得分:1)

您添加的内容似乎不是JSON格式。

以下是我的建议:

  1. Map<String, String>

    中准备您的内容
    Map<String, String> inputMap = new HashMap<String, String>();  
    inputMap.put("day", String.valueOf(5));
    
  2. 将其转换为JSON,例如使用Gson(将gson添加到Maven或放到您的资源文件夹中):

    private static final Gson gson = new 
    GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
    

    然后使用gson.toJson(inputMap)转换准备好的地图。

  3. 包含JSON格式内容的结果字符串会像这样添加到httppost

    BasicHttpEntity httpEntity = new BasicHttpEntity();
    
    httpEntity.setContent(new ByteArrayInputStream(jsonContent.getBytes()));           
    httppost.setEntity(httpEntity);
    

答案 2 :(得分:0)

它会起作用:

    httpPost.addHeader(BasicScheme.authenticate(
            new UsernamePasswordCredentials("email", "password"), "UTF-8", false));