Last active
September 16, 2017 03:24
-
-
Save melihmucuk/6786133 to your computer and use it in GitHub Desktop.
Getting JSON data over SSL on Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Util { | |
static JSONObject jObj = null; | |
static String json = ""; | |
public Util(){} | |
public JSONObject GetJSON(String URL) throws JSONException{ | |
try { | |
final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { | |
@Override | |
public boolean verify(String hostname, SSLSession session) { | |
return true; | |
} | |
}; | |
URL url = new URL(URL); | |
HttpsURLConnection httpURLConnection = (HttpsURLConnection) url.openConnection(); | |
httpURLConnection.setRequestProperty("Content-Type","0"); | |
httpURLConnection.setRequestMethod("GET"); | |
httpURLConnection.setUseCaches(false); | |
httpURLConnection.setConnectTimeout(10000); | |
httpURLConnection.setReadTimeout(10000); | |
httpURLConnection.setAllowUserInteraction(false); | |
httpURLConnection.setInstanceFollowRedirects(true); | |
httpURLConnection.setHostnameVerifier(DO_NOT_VERIFY); | |
httpURLConnection.connect(); | |
int status = httpURLConnection.getResponseCode(); | |
switch (status) { | |
case 200: | |
case 201: | |
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); | |
StringBuilder sb = new StringBuilder(); | |
String line; | |
while ((line = br.readLine()) != null) { | |
sb.append(line+"\n"); | |
} | |
br.close(); | |
json = sb.toString(); | |
jObj = new JSONObject(json); | |
} | |
} catch (UnsupportedEncodingException e) { | |
e.printStackTrace(); | |
} catch (ClientProtocolException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} catch (IllegalStateException e) { | |
e.printStackTrace(); | |
} | |
return jObj; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment