HttpGet,HttpClient,HttpResponse,HttpEntity,EntityUtils deprectated

时间:2016-03-23 04:47:27

标签: java android apache-httpclient-4.x apache-httpcomponents

我正在使用android studio API 23,我有这些警告 deprecated warning

这是我的代码

@Override
    protected Boolean doInBackground(String... urls) {
        String strNama[], strDeskripsi[], strFoto[], strMarker[], strLng[], strLat[];

        try {
            HttpGet httppost = new HttpGet(urls[0]);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httppost);
            int status = response.getStatusLine().getStatusCode();
            if (status == 200) {
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);
                JSONObject jsono = new JSONObject(data);
                JSONArray konten = jsono.getJSONArray("konten");
                strNama = new String[konten.length()];
                strDeskripsi = new String[konten.length()];
                strFoto = new String[konten.length()];
                strMarker = new String[konten.length()];
                strLat = new String[konten.length()];
                strLng = new String[konten.length()];
                for (int i = 0; i < konten.length(); i++) {
                    JSONObject object = konten.getJSONObject(i);
                    strNama[i] = object.getString("nama");
                    strDeskripsi[i] = object.getString("deskripsi");
                    strFoto[i] = object.getString("foto");
                    strMarker[i] = object.getString("marker");
                    strLat[i] = object.getString("lat");
                    strLng[i] = object.getString("lng");
                    Actors actor = new Actors();
                    actor.setName(strNama[i]);
                    actor.setDescription(strDeskripsi[i]);
                    actor.setImage(strFoto[i]);
                    actor.setMarker(strMarker[i]);
                    actor.setLat(strLat[i]);
                    actor.setLng(strLng[i]);
                    actorsList.add(actor);
                }
                return true;
            }

        } catch (ParseException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

这是模块

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "com.krb.navigasi.petakebunrayabogor"
        minSdkVersion 10
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

它在Android 5.0中运行良好,但我怎样才能解决这些警告?我希望有人可以帮我修改上面的代码。任何帮助将不胜感激。

提前致谢。

2 个答案:

答案 0 :(得分:2)

由于已经回答过所提到的类已被弃用,Android文档建议您使用HttpURLConnection,您可以自己处理网络调用,确保将它们写在主线程之外。

下面给出了一个示例,您可以使用POST

HttpURLConnection实体 HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("POST"); // hear you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc. httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json` httpURLConnection.connect();
HttpURLConnection

当您将某些数据发布到 JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("para_1", "arg_1"); jsonObject.addProperty("para_2", "arg_2"); DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream()); wr.writeBytes(jsonObject.toString()); wr.flush(); wr.close(); 的实例时,您可以这样做......

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

由于这个类与android框架捆绑在一起,不需要添加任何库,但我建议你使用像OkHTTP这样的东西,

这将处理其他线程的网络调用,给出的示例显示了如何发布

    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

        }
    });

此示例在主线程上调用网络调用,您希望像这样进行入队

function accupdate() {
debugger;
var PrvdLocData;
var name;
var age;
var sex;
var address;
var phonenumber;
var degree;
var sslcpercentage;
var hscpercentage;
var ugpercentage;

var PrvdLocData = new Array();

var EmpId = Xrm.Page.data.entity.getId();

//parent fields
if (Xrm.Page.getAttribute("new_name").getValue() != null) {
    name = Xrm.Page.getAttribute("new_name").getValue();
}

if (Xrm.Page.getAttribute("new_age").getValue() != null) {
    age = Xrm.Page.getAttribute("new_age").getValue();
}

if (Xrm.Page.getAttribute("new_sex").getValue() != null) {
    sex = Xrm.Page.getAttribute("new_sex").getValue();
}

if (Xrm.Page.getAttribute("new_address").getValue() != null) {
    address = Xrm.Page.getAttribute("new_address").getValue();
}

if (Xrm.Page.getAttribute("new_phonenumber").getValue() != null) {
    phonenumber = Xrm.Page.getAttribute("new_phonenumber").getValue();
}

if (Xrm.Page.getAttribute("new_degree").getValue() != null) {
    degree = Xrm.Page.getAttribute("new_degree").getValue();
}

if (Xrm.Page.getAttribute("new_sslcpercentage").getValue() != null) {
    sslcpercentage = Xrm.Page.getAttribute("new_sslcpercentage").getValue();
}

if (Xrm.Page.getAttribute("new_hscpercentage").getValue() != null) {
    hscpercentage = Xrm.Page.getAttribute("new_hscpercentage").getValue();
}

if (Xrm.Page.getAttribute("new_ugpercentage").getValue() != null) {
    ugpercentage = Xrm.Page.getAttribute("new_ugpercentage").getValue();
}


var context = Xrm.Page.context;
var serverurl = context.getClientUrl();
var ODatapath = serverurl + "/XRMServices/2011/OrganizationData.svc";
var retrieveResult = new XMLHttpRequest();
var dtqeurl = ODatapath + "/new_conSet?$select=new_name,new_YourAge,new_YourSex,new_HomeAddress,new_Contact,new_DegreeType,new_SSLCPercent,new_HSCPercent,new_conId,new_UGPercent&$filter=new_AccName/Id eq guid'" + EmpId + "'";
GetRecs("PrvtLoc", dtqeurl);

function GetRecs(entity, url) {
    jQuery.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: url,
        async: false,
        beforeSend: function XMLHttpRequest(XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/json");

        },
        success: function (data, textStatus, XmlHttpRequest) {
            if (data && data.d != null && data.d.results != null) {
                AddRecordsToArray(data.d.results, entity);

            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            //  alert("Error :  has occured during retrieval of the records ");
        }
    });
}

function AddRecordsToArray(result, entity) {
    $.each(result, function () {

        if (entity == "PrvtLoc")
            PrvdLocData.push(this);


    });
}
if (PrvdLocData.length > 0) {

    for (i = 0; i < PrvdLocData.length; i++) {

        //Object Assigning

        var crmobject = new Object();

        //Variable declaration for Child entity's primarykey (ID)

        var childId = PrvdLocData[i].new_conId;

        //Setting child entitiy's value with parent entity's variable

            crmobject.new_name = name;
            crmobject.new_YourAge = parseInt(age);
            crmobject.new_YourSex = sex;
            crmobject.new_HomeAddress = toString(address);
            crmobject.new_Contact = parseInt(phonenumber);
            crmobject.new_DegreeType = degree;
            crmobject.new_SSLCPercent = sslcpercentage;
            crmobject.new_HSCPercent = hscpercentage;
            crmobject.new_UGPercent = ugpercentage;


        // update starts...

    var serverUrl = Xrm.Page.context.getClientUrl();

    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    var crmobject = new Object();
    // Specify the ODATA entity collection 
    var ODATA_EntityCollection = "/new_conSet";
    var jsonEntity = window.JSON.stringify(crmobject);
        //Asynchronous AJAX function to Create a CRM record using OData 
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + "(guid'" + childId + "')",
            data: jsonEntity,
            beforeSend: function (XMLHttpRequest) {
                //Specifying this header ensures that the results will be returned as JSON. 
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
                XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
            },
            success: function (data, textStatus, XmlHttpRequest) {
                alert("updated");



            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("fail to update");
            }
        });
    }


}

答案 1 :(得分:0)

只需初始化,然后同步

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.cli‌​ent:4.1.2'