带有基本身份验证 java 的 Http 请求 [英] Http request with basic auth java

查看:45
本文介绍了带有基本身份验证 java 的 Http 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过具有基本身份验证的 httpGet 访问 API.我的代码是:

I am trying to access an API via httpGet with basic auth. My code is:

byte[] encodedBytes = Base64.getEncoder().encode("user:pass".getBytes());

HttpGet httpget = new HttpGet("https://app.feedcheck.co/api/reviews");
httpget.setHeader("Authorization", "Basic " + encodedBytes);

System.out.println("executing request " + httpget.getRequestLine());
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
String apiOutput = EntityUtils.toString(entity);
System.out.println(apiOutput);

在邮递员中,我得到了预期的响应,但在 Eclipse 中运行程序时,它返回:

In postman I get the response I expect but when running the program in Eclipse it returns:

无法验证您对该网址的访问级别.你必须登录具有适当的凭据

Could not verify your access level for that URL. You have to login with proper credentials

在 Python 中使用代码执行请求时:

When doing the request in Python with code:

import requests
from requests.auth import HTTPBasicAuth

r = requests.get('https://app.feedcheck.co/api/reviews', auth=HTTPBasicAuth('user', 'pass'))
print(r.text)

它返回与 Postman 相同的结果.谁能帮我这个?我做错了什么?

it returns the same as Postman. Can anyone help me with this? What am I doing wrong?

推荐答案

检查这个.它对我有用.

Check this. It worked for me.

  try {
        String webPage = "http://192.168.1.1";
        String name = "admin";
        String password = "admin";

        String authString = name + ":" + password;
        System.out.println("auth string: " + authString);
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        System.out.println("Base64 encoded auth string: " + authStringEnc);

        URL url = new URL(webPage);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        InputStream is = urlConnection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);

        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuffer sb = new StringBuffer();
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }
        String result = sb.toString();

        System.out.println("*** BEGIN ***");
        System.out.println(result);
        System.out.println("*** END ***");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

这篇关于带有基本身份验证 java 的 Http 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆