HTTPClient je zastaralý, takže byste se mu měli vyhnout. Podívejte se na tento HttpClient je zastaralý (android studio , Target=api 22)
Toto je moje pracovní funkce pro získání obsahu z json
public static JSONObject getJSONfromURL(final String URL){
JSONObject jArray = null;
try {
//URL = "http://emedteam-001-site1.ctempurl.com/emed/home/getdrug?letter=a";
URLConnection conn = new URL(URL).openConnection();
conn.addRequestProperty("Accept", "application/json");
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String str = sb.toString();
sb = null;
jArray = new JSONObject(str);
} catch (Exception e) {
e.printStackTrace();
}
return jArray;
}
UPRAVENO: Tuto funkci musíte volat uvnitř AsyncTask, abyste se vyhnuli Jak opravit android.os.NetworkOnMainThreadException ?
ListView lv;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new StackOverflowTask().execute();
}
});
class StackOverflowTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... urls) {
try {
JSONObject test = JSONfunctions.getJSONfromURL("http://emedteam-001-site1.ctempurl.com/emed/home/getdrug?letter=a");
return test;
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(JSONObject test) {
if(test != null)
Toast.makeText(TestActivity.this, "Hello Stackoverflow ;)",Toast.LENGTH_SHORT).show();
}
}
Doufám, že to pomůže!