我想将请求方法从GET更改为POST.这是我的代码:
HttpURLConnection connection = null;
URL url = new URL("https://accounts.google.com/o/oauth2/token");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
Run Code Online (Sandbox Code Playgroud)
但正如您在调试请求的方法时在此图像中看到的那样不会改变:

我需要联系服务器以使用HTTP服务.
尝试使用浏览器访问服务,使用https://example.com/service基本身份验证对话框.
更改URL以https://username:password@example.com/service轻松绕过它.
尝试使用Ajax做同样的事情总是导致401 Unauthorized:
$.ajax({
url: 'https://username:password@example.com/service',
// rest repeats
type: "GET",
async: true,
success: function(text) { alert('success'); },
error: function (text) { alert('error') },
complete: function(text) { alert('complete'); }
});
Run Code Online (Sandbox Code Playgroud)
$.ajax({
url: 'https://example.com/service',
username: username,
password: password,
// snip repeat
});
Run Code Online (Sandbox Code Playgroud)
$.ajax({
url: 'https://example.com/service',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic "
+ btoa(username + ":" + password));
},
// snip repeat
});
Run Code Online (Sandbox Code Playgroud)