本文介绍了具有基本身份验证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:
在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)
返回与邮递员相同的信息.谁能帮我这个?我在做什么错了?
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请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!