Android implements request HTTP authentication

Posted by bradleybebad on Fri, 10 Jul 2020 16:54:06 +0200

These days, the development of external SDK, can achieve landing, payment.Similar to developing a set of QQ, WeChat third party login.The authorization protocol used is OAuth 2.0.Among them, Http Authentication is used, and you can consult the online materials. There are all kinds of answers, some don't know if they have been verified, and some API s have expired.

If you can compare Authentication requests using the Charles tool


         


Fig.1 is a Post request with authentication settings, and Fig.2 is a general Post network request

The first line of code is OKhttp's own way to add OAuth, but this way of debugging has been unsuccessful and no reason has been found. If you have successfully requested approval in this way, you can mention a note.

//The first parameter is the user name and the second parameter is the password
final String basic = Credentials.basic("zhangsan", "123456");
OkHttpClient client = new OkHttpClient.Builder()
        .authenticator(new Authenticator() {
            @Override
            public Request authenticate(Route route, Response response) throws IOException {
                return response.request().newBuilder().header("Authorization", basic).build();
            }
        })
        .build();
Request request = new Request.Builder().url("http://192.168.45.2:8080/ha").build();
client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        Log.d("--------", "onFailure: "+e.getMessage());
    }


    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response.isSuccessful()) {
            Log.d("---------", "onResponse: "+response.body().string());
        }
    }
});


There are also Http put forms

 public static void invoke() {
        try {
            String url = "http://xxxxxx";
            HttpGet httpReq = new HttpGet(url);
            httpReq.addHeader(BasicScheme.authenticate(
                    new UsernamePasswordCredentials("Hello", "123456"),
                    "UTF-8", false));
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse httpResponse = httpClient.execute(httpReq);
            StringBuilder builder = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpResponse.getEntity().getContent()));
            for (String s = reader.readLine(); s != null; s = reader.readLine()) {
                builder.append(s);
            }
            String result = builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

HttpGet can use HttpUrlConnection when it is already in the Android API


HttpPost

public static void getUserData() {
        //1. Create an instance of HttpClient
        try {
            //Encrypt with base64
            //Send authentication information to header
            final String tokenStr = Base64.encode(("testclient" + ":testpass").getBytes());
            HashMap<String, String> hashMap = new HashMap<String, String>();
            String paramsStr = Utility.getHttpParamsStr(hashMap);
            StringEntity stringEntity = new StringEntity(paramsStr);
            stringEntity.setContentType("application/x-www-form-urlencoded");
            HttpPost post = new HttpPost(API.loginCode);
            post.setHeader("Content-Type", "application/json");
            post.setHeader("Authorization", tokenStr);
            HttpClient client = new DefaultHttpClient();
            HttpResponse httpResponse = client.execute(post);
            String result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            Logger.i("--------invoke--", "ClientProtocolException " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Logger.i("--------invoke--", "IOException " + e.getMessage());
            e.printStackTrace();
        }
    }


HttpPost also belongs to an obsolete API


public class HttpUtils {


    /*
    * Function  :   Send Post Request to Server
    * Param     :   params Request body content, encode encoding format
    */
    public static String submitPostData(String strUrlPath, Map<String, String> params, String encode) {
        byte[] data = getRequestData(params, encode).toString().getBytes();//Get Requestor
        try {
            URL url = new URL(strUrlPath);
            Logger.i("-------getUserId---", "url " + url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setConnectTimeout(3000);     //Set connection timeout
            httpURLConnection.setDoInput(true);                  //Open the input stream to get data from the server
            httpURLConnection.setDoOutput(true);                 //Open the output stream to submit data to the server
            httpURLConnection.setRequestMethod("POST");     //Set up data submission as Post
            httpURLConnection.setUseCaches(false);               //Cache cannot be used with Post
            //Set the type of requester to be text type
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            //Set Requestor Length
            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
            //Get the output stream and write data to the server
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(data); //   data is actually a string spliced by key=value in map
            final String tokenStr = "Basic " + Base64.encode(("Hello" + ":123456").getBytes());
            httpURLConnection.addRequestProperty("Authorization", tokenStr);

            int response = httpURLConnection.getResponseCode();            //Get the server's response code
            if(response == HttpURLConnection.HTTP_OK) {
                InputStream inptStream = httpURLConnection.getInputStream();
                return dealResponseResult(inptStream);                     //Processing server response results
            }
        } catch (IOException e) {
            //e.printStackTrace();
            return "err: " + e.getMessage().toString();
        }
        return "-1";
    }

    public static StringBuffer getRequestData(Map<String, String> params, String encode) {
        StringBuffer stringBuffer = new StringBuffer();        //Store encapsulated request body information
        try {
            for(Map.Entry<String, String> entry : params.entrySet()) {
                stringBuffer.append(entry.getKey())
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(), encode))
                        .append("&");
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);    //Delete the last'&'
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuffer;
    }

    /*
     * Function  :   Processing server response results (converting input stream to string)
     * Param     :   inputStream Response input stream from server
     */
    public static String dealResponseResult(InputStream inputStream) {
        String resultData = null;      //Store processing results
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        try {
            while((len = inputStream.read(data)) != -1) {
                byteArrayOutputStream.write(data, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        resultData = new String(byteArrayOutputStream.toByteArray());
        Logger.i("-------getUserId---", "dealResponseResult " + resultData);
        return resultData;
    }

}


  final String tokenStr = "Basic " + Base64.encode(("Hello" + ":123456").getBytes());
 httpURLConnection.addRequestProperty("Authorization", tokenStr);   

The key to setting up Authentication is that Base64 sets the username and password toName:keyEncrypt by way, then add to

After "Basic", the second server will parse according to the Oauth framework.

Use Php as an example to get the username field PHP_AUTH_USER, password is PHP_AUTH_PW.

Recommended HttpUtils




Topics: SDK network OkHttp Android