我正在构建一个需要oauth 2身份验证的应用。检索 access_token 的端点是https://10.0.2.2:8443/oauth/token
(10.0.2.2是环回到主机上的localhost)
当我通过浏览器执行请求时,它工作正常,但是当我通过Java代码执行此操作时,我收到了一个错误的请求,并且我没有获得足够的信息来进行故障排除。
我使用不安全的HttpClient(是的,我知道,这非常不安全)
public class UnsafeHttpsClient {
public static HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(sf.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 8080));
registry.register(new Scheme("https", sf, 8443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
}
我也使用这个课程。代码取自SO上的这篇文章: 参考:Trusting all certificates using HttpClient over HTTPS
public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
最后,我使用这两个类来构建我的请求:
public class TaskAuthenticate extends AsyncTask<String, Integer, JSONArray> {
private Context ctx;
public IApiAccessResponse delegate=null;
private HttpClient mHttpclient = UnsafeHttpsClient.getNewHttpClient();
private HttpPost mHttppost;
private String client_string = "mobile:";
public TaskAuthenticate (Context ctx) {
this.ctx = ctx;
}
protected JSONArray doInBackground(String... params) {
String strTokenUrl = ctx.getResources().getString(R.string.oauth2_endpoint);
mHttppost = new HttpPost();
try {
mHttppost.setURI(new URI(strTokenUrl));
}
catch (URISyntaxException e1) {
e1.printStackTrace();
}
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("username", params[0]));
nameValuePairs.add(new BasicNameValuePair("password", params[1]));
nameValuePairs.add(new BasicNameValuePair("grant_type", "password"));
nameValuePairs.add(new BasicNameValuePair("client_id", "mobile"));
// nameValuePairs.add(new BasicNameValuePair("client_secret",));
try {
String header = "Basic " + Base64.encodeToString(client_string.getBytes("UTF-8"), Base64.DEFAULT);
mHttppost.setHeader("Authorization", header);
mHttppost.setHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
mHttppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpResponse response;
try {
response = mHttpclient.execute(mHttppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
response = null;
} catch (IOException e) {
e.printStackTrace();
response = null;
}
JSONArray result = null;
try {
result = new JSONArray(EntityUtils.toString(response.getEntity()));
} catch (ParseException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
当我执行此操作时,我收到400 - Bad request
响应。此外,如果我尝试使用以下代码获取响应正文
HttpEntity respEntity = response.getEntity();
if(respEntity!=null) {
String res = EntityUtils.toString(respEntity);
}
身体以空绳子的形式回来 到目前为止,我无法在浏览器中重现,所以我对问题可能是什么感到无能为力。 有什么我从根本上做错了吗?任何调试此技巧的提示都将受到赞赏
如果需要服务器代码,我会发布,但我认为问题出在应用程序中,因为我可以在浏览器中执行请求。
答案 0 :(得分:0)
我弄清楚问题是什么。当你为你的请求添加一个标题时出现,行尾字符只会导致POST请求出现问题。解决方法是更改位掩码以确保不存在行尾字符。我替换了这一行:
String header = "Basic " + Base64.encodeToString(client_string.getBytes("UTF-8"), Base64.DEFAULT);
由:
String header = "Basic " + Base64.encodeToString(client_string.getBytes("UTF-8"), Base64.URL_SAFE|Base64.NO_WRAP);