我正在做一个可以添加的AsyncTask 如果我把我的sdk降低到22。
在sdk 23上它根本不起作用,即使在22岁,它也为我写了一些内容。
我在做错了什么? 或者如何纠正它以便我可以在sdk 23运行它?@Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
//this gets us the actors node and puts it in jarray veriable
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
//the object veriable will be the node in position i inside the "actors" node in the main json
JSONObject object = jarray.getJSONObject(i);
Log.d("myAppLog", "next one is: ");
Log.d("myAppLog", object.getString("name"));
actorClass actorClassVeriable = new actorClass();
actorClassVeriable.setName(object.getString("name"));
actorClassVeriable.setDescription(object.getString("description"));
actorClassVeriable.setDob(object.getString("dob"));
actorClassVeriable.setCountry(object.getString("country"));
actorClassVeriable.setHeight(object.getString("height"));
actorClassVeriable.setSpouse(object.getString("spouse"));
actorClassVeriable.setChildren(object.getString("children"));
actorClassVeriable.setImage(object.getString("image"));
actorsList.add(actorClassVeriable);
}
return true;
}
//------------------>>
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
答案 0 :(得分:7)
来自文档,
Android 6.0版本删除了对Apache HTTP客户端的支持。如果您的应用使用此客户端并定位到Android 2.3(API级别9)或更高版本,请改用HttpURLConnection类。此API更高效,因为它通过透明压缩和响应缓存减少了网络使用,并最大限度地降低了功耗。要继续使用Apache HTTP API,必须首先在build.gradle文件中声明以下编译时依赖项:
android {
useLibrary 'org.apache.http.legacy'
}
答案 1 :(得分:3)
HttpGet,HttpClient,HttpResponse和HttpEntity 被贬低。
现在你必须使用HttpUrlConnection
public class Info {
private Info(){
// Exists only to defeat instantiation.
this.list = new ArrayList<>();
}
public static Info info = null;
public static Info getinstance(){
if(info == null) info = new Info();
return info;
}
private ArrayList<Object> list;
public Info(){
this.list = new ArrayList<>();
}
public Info getInfo(){
return this;
}
public void put(final byte[] macAddress, final String name) {
HashMap<byte[], String> map = new HashMap<>();
map.put(macAddress,name);
list.add(map);
}
public ArrayList getList(){
return list;
}