okhttp请求401Unauthorized验证问题

一、使用okhttp时:

okhttp添加auth验证

public String post(String url, String json,String username,String password) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        String credential = Credentials.basic(username,password);//对应的用户名密码
        Request request = new Request.Builder()
                .header("Authorization", credential)//添加auth验证
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

username和password对应的auth需要的用户名密码:通过一下方法可以获取用户名密码

        URL _url = new URL(url);
        String[] userInfoArray =_url.getUserInfo().split(":");
		String userName = userInfoArray[0];
		String password = userInfoArray[1];

二、使员工httpclient时:

参考一下文章:

https://blog.csdn.net/qq_27605885/article/details/79131483

你可能感兴趣的:(javaWeb)