HTTPClient ist veraltet, daher sollten Sie es vermeiden. Sehen Sie sich diesen HttpClient ist veraltet (android studio , Ziel=api 22)
Dies ist meine Arbeitsfunktion, um Inhalte von json abzurufen
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;
}
BEARBEITET: Sie müssen diese Funktion innerhalb von AsyncTask aufrufen, um How to fix android.os.NetworkOnMainThreadException zu vermeiden ?
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();
}
}
Ich hoffe, es hilft!