我尝试使用HttpsURLConnection
命中我的服务器,得到响应代码401 - 需要进行身份验证。尝试以下方法:
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("myuser", "!mypassword".toCharArray());
}
});
获得响应代码400 - 错误请求。
根据一些stackoverflow研究,我也尝试使用:
String authorizationString = "Basic " + Base64.encodeToString(("username" + ":" + "password").getBytes(), Base64.DEFAULT);
conn.setRequestProperty("Authorization", authorizationString);
同样的问题,代码400.我也信任所有使用@Chrispix方法的主机: Trust Anchor not found for Android SSL Connection 不确定这是否会以某种方式干扰,但这是针对原型而且网站证书无效,所以我需要绕过检查。
使用这些属性设置连接,不确定是否有任何错误或缺失:
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.addRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoInput(true);
谢谢!
答案 0 :(得分:1)
如何使用HttpClient
?
HttpClient httpClient= new DefaultHttpClient();
HttpGet httpGet= new HttpGet(yourUrl);
String authString = (yourUserName+":"+yourPassword);
httpGet.addHeader("Authorization", "Basic " +
Base64.encodeToString(authString.getBytes(),Base64.DEFAULT));
HttpResponse response = httpClient.execute(httpGet);
似乎你想通过目前的证书检查,这个相关的链接可能会帮助你
答案 1 :(得分:0)
试试这种方式
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
return result;
}
params参数应该采用这种格式
public String authenticateUser(String username, String password)
{
String params = "username="+ URLEncoder.encode(username,"UTF-8") +
"&password="+ URLEncoder.encode(password,"UTF-8") +
"&";
String result = socketOperator.sendHttpRequest(params);
return result;
}
将此功能称为认证...
答案 2 :(得分:0)
似乎我得到了正确的响应 - 我认为400意味着格式错误的请求,但检查错误流我发现请求很好,但参数错误。菜鸟错误!