Problems to receive JSON from https server on Android
this is my question/problem:
I'm making a URL request to a server that authenticates by SSL through https, but when I get the answer always returns empty when I convert the input to string. Another call without parameters always runs smoothly
Any ideas?
URL: https://www.server.com/api/getResources.php?res[]=Argentina&res[]=Australia&res[]=Bolivia
And the code:
HttpURLConnection http = conectar(URL);
InputStream urlInputStream = null;
try {
urlInputStream = http.getInputStream();
} catch (IOException e) {
}
conectar method:
private HttpURLConnection conectar(String surl) {
URL url = null;
try {
url = new URL(surl);
} catch (MalformedURLException e) {
}
HttpURLConnection http = null;
if (url.getProtocol().toLowerCase().equals("https")) {
trustEveryone();
HttpsURLConnection https = null;
try {
https = (HttpsURLConnection) url.openConnection();
} catch (IOException e) {
}
// https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
} else {
try {
http = (HttpURLConnection) url开发者_Python百科.openConnection();
} catch (IOException e) {
}
}
Authenticator.setDefault(new MyAuthenticator());
return http;
}
trustEveryone method:
HttpsURLConnection
.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname,
SSLSession session) {
return true;
}
});
SSLContext context = SSLContext.getInstance("TLS"); // TLS
context.init(null, new X509TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
} }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
Is the URL string you posted correct? If so you need to encode the square brackets before passing it into the URL
constructor. The documentation for URL
states:
The URL class does not itself encode or decode any URL components according to the escaping mechanism defined in RFC2396. It is the responsibility of the caller to encode any fields, which need to be escaped prior to calling URL, and also to decode any escaped fields, that are returned from URL
EDIT
RFC2396 states that:
Data corresponding to excluded characters must be escaped in order to be properly represented within a URI.
The square brackets are counted as excluded characters.
As such you need to encode the parameter string prior to including it in the URL. You don't want to encode the whole URL as otherwise it will encode characters such as :
. Here is a code snippet:
String parameters = "res[]=Argentina&res[]=Australia&res[]=Bolivia";
String encodedParameters = URLEncoder.encode(parameters , "UTF-8");
You can then append this to your host & path and pass it into your URL
constructor.
精彩评论