简体   繁体   English

Android的HTTP身份验证

[英]http authentication with android

I have a problem with a http authentication. 我的http认证有问题。 No problem to connect with other web-service without authentication. 无需身份验证即可与其他Web服务连接。 But I don't know how i can connect to this http authentication with android. 但我不知道我该如何使用android连接到此http身份验证。 So in my app, i have two textfield (login and password). 因此,在我的应用程序中,我有两个文本字段(登录名和密码)。 And a button to connect to an address and get informations about the user (json data). 还有一个按钮,用于连接到地址并获取有关用户的信息(json数据)。 In a first time, i would like to pass identifiers in adress : https://proxyepn-test.epnbn.net/wsapi/user . 第一次,我想在地址中传递标识符: https : //proxyepn-test.epnbn.net/wsapi/user Like https://login:password@proxyepn-test.epnbn.net/wsapi/user . https:// login:password@proxyepn-test.epnbn.net/wsapi/user一样 And display data ine the log. 并在日志中显示数据。 Can you help me ? 你能帮助我吗 ?

` I try this. 我尝试一下。

public HashMap<String, String> btn_connexion(View view) {
    etPseudo = (EditText) findViewById(R.id.editText);
    etMdp = (EditText) findViewById(R.id.editText2);
    final String pseudo = etPseudo.getText().toString();
    final String mdp = etMdp.getText().toString();


    //String urldisplay = "https://" + pseudo + ":" + mdp + "@proxyepn-test.epnbn.net/wsapi/user";

    @Override
    public Map<String, String> getHeaders() throws AuthFailureErro {
        HashMap<String, String> params = new HashMap<>();
        String creds = String.format("%s:%s", pseudo, mdp);
        String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.NO_WRAP);
        params.put("Authorization", auth);
        return params;


    }



}`

//class to establish the connection //建立连接的类

public static class RestOperation extends AsyncTask<String, Void, String> {

    String content;
    String error;
    String data = "";


    @Override
    protected String doInBackground(String... params) {
        BufferedReader br = null;

        URL url;
        try {
            url = new URL(params[0]);

            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);

            OutputStreamWriter outputStreamWr = new OutputStreamWriter(connection.getOutputStream());
            outputStreamWr.write(data);
            outputStreamWr.flush();

            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            while((line = br.readLine())!=null) {
                sb.append(line);
                sb.append(System.getProperty("line.separator"));
            }

            content = sb.toString();
            Log.i("content",content);

        } catch (MalformedURLException e) {
            error = e.getMessage();
            e.printStackTrace();
        } catch (IOException e) {
            error = e.getMessage();
            e.printStackTrace();
        } finally {
            try {
                if(br != null) {
                    br.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return content;
    }

}

//an example of connection with a web-service without authentication //没有身份验证的与Web服务的连接示例

String restURL = "https://proxyepn-test.epnbn.net/wsapi/epn";
    RestOperation test = new RestOperation();
    String[]tabInfos = null;
    try {

        String test2 = test.execute(restURL).get().toString();
        Log.i("result",test2);

        JSONObject obj = new JSONObject(test2);
        JSONObject data = obj.getJSONObject("data");
        Iterator<String> iterator = data.keys();
        while(iterator.hasNext()){
            String key = iterator.next();
            String name = data.getString(key);

            tabInfos = name.split(",");


            ...



            }
        }

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

Encode your username and password to base64 string and pass to header of your request in Authorization key. 将您的用户名和密码编码为base64字符串,并在Authorization密钥中传递给您的请求标头。

You can use volley library and pass username and password in header as: 您可以使用排球库,并在标头中通过以下方式传递用户名和密码:

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> params = new HashMap<>();
            String creds = String.format("%s:%s", "your-username", "your-password");
            String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.NO_WRAP);
            params.put("Authorization", auth);
            return params;
        }

If you are using HttpUrlConnection then pass basic auth in header as: 如果您使用的是HttpUrlConnection则在标头中传递基本身份验证为:

        String creds = String.format("%s:%s", "your-username", "your-password");
        String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.NO_WRAP);
        yourHttpUrlConnection.setRequestProperty("Authorization", auth);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM