java - 当身份验证凭据正确时,http post 请求返回 401 -
问题描述
我仅在发布数据时遇到此问题,我得到了 401(未经授权),而我的凭证是正确的!如何解决这个问题?
ttpURLConnection urlConnection;
IgnoreSSL();
String url = null;
url = "http://" + nmap_node.getHost() + ":"+nmap_node.getPort() + "/post";
String result = null;
try {
String userpass = user_name + ":" + password; //stored in the class
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
//Connect
urlConnection = (HttpURLConnection) ((new URL(url).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "Basic "+basicAuth);
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(10000);
urlConnection.connect();
//data
String data = datajson.toString(); //method return json to use
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();
int responseCode=urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
}else {
// return new String("false : "+responseCode);
new String("false : "+responseCode);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
我在 Linux 中尝试使用 curl 命令它运行良好 - 我得到响应 200 并在屏幕上打印结果。
解决方案
推荐阅读
- java - 当java中的计时器倒计时结束时,如何制作弹出消息窗口?
- rubymine - 无法使用 rspec 在 rubymine 中进行调试
- android - 我可以在同一个字段中使用 WhereEqualTo 两次吗?
- javascript - 如何创建一个 10 分钟计时器,使用 Javascript 以 HTML 格式自动提交表单。(空白字段在提交后自动设置为 0)
- git - 当我在 master 上使用 BFG Repo-Cleaner 时其他分支会发生什么
- css - 在 CSS3 中,flex-grow 为 0.1 的 flex 项目应该占用所有额外空间还是只占用 10%?
- arrays - 在一个键上比较2个字典数组并合并在一起
- elasticsearch - 带有条件的嵌套字段上的 Elasticsearch 查询
- nativescript - 如何在本机脚本中以编程方式获取应用程序名称
- wordpress - ssl 在我的 wordpress 网站的 2 页中不起作用