Java / Android:如何更新不推荐使用的org.apache.http

时间:2016-03-24 10:40:39

标签: java android android-studio push-notification google-cloud-messaging

我的Andoird应用程序需要注册设备的令牌才能进行推送通知。到目前为止,我一直使用这段代码:

final HttpClient httpclient = new DefaultHttpClient();
final HttpPost httppost = new HttpPost("http://mysite/registration.php");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Log.e("token:", token);
Log.e("android_id:", android_id );
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("token", token));
nameValuePairs.add(new BasicNameValuePair("device", android_id));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); /***/
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost); /***/
String responseBody = EntityUtils.toString(response.getEntity()); /***/

无论如何,Android Studio继续告诉我们这段代码已被弃用,我希望我不会被迫添加Apache依赖。例如,我不想拥有

dependencies {
  compile group: 'org.apache.httpcomponents' , 
  name: 'httpclient-android' , 
  version: '4.3.5.1'
}

在我的build.gradle中。

那么,我该如何更新我的代码呢?特别是,我很难理解如何用/ *** /来更新这些行。 感谢您的关注

2 个答案:

答案 0 :(得分:0)

如果你想摆脱Apache依赖,你可以切换到$crawler->filter('div#product > div.row > div.span6 > div.thumbs > div.image a')->slice(1, 5)->each(function($node, $i) use(&$local, $lowertitle){ $filename = "images/galatea" . $lowertitle . $i . ".jpg"; $imageurl = $node->attr('href'); $theurl = substr($imageurl, 2); copy('http://'.$theurl, $filename); $imagesarray = $local['images'][] = $filename; }); ,这是Android的Java实现的一部分。这是文档中的简单GET示例:

HttpURLConnection

您的案例有点复杂,因为您通过setEntity()发布数据。以下答案说明了如何使用URL url = new URL("http://www.android.com/"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); readStream(in); finally { urlConnection.disconnect(); } 执行此操作:

https://stackoverflow.com/a/13486223/6055238

答案 1 :(得分:0)

您可能还想尝试或至少看看android的Volley。它有很多教程。这是一个示例代码:

RequestQueue queue = Volley.newRequestQueue(getActivity());
    StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {
            try{
                JSONArray array = new JSONArray(s.toString());
                //getting response here
               }
            catch(Exception e){
               }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<String, String>();
            Log.wtf("PID HERE", pid);
            params.put("token", token);
            params.put("device", android_id);
            return params;
        }
    };queue.add(sr);