【问题标题】:Deprecated HTTP Classes Android lollipop 5.1已弃用的 HTTP 类 Android lollipop 5.1
【发布时间】:2015-06-14 16:26:36
【问题描述】:

org.apache.http 类和 AndroidHttpClient 类已在 Android 5.1 中弃用。这些类不再维护,您应该尽快将使用这些 API 的任何应用代码迁移到 URLConnection 类。

https://developer.android.com/about/versions/android-5.1.html#http

建议切换到 URLConnection 类。没有足够的文档确切地说明如何从应用程序发出后调用。

目前我正在使用这个

public void postData()
{
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

    try
    {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
     } 
     catch (ClientProtocolException e) 
     {
        // TODO Auto-generated catch block
     } 
     catch (IOException e) 
     {
        // TODO Auto-generated catch block
     }
} 

我如何使用 UrlConnections 来做到这一点?

【问题讨论】:

标签: android http-post


【解决方案1】:

想到使用 HttpUrlConnection 分享我的代码

public String  performPostCall(String requestURL,
            HashMap<String, String> postDataParams) {

        URL url;
        String response = "";
        try {
            url = new URL(requestURL);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);


            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line=br.readLine()) != null) {
                    response+=line;
                }
            }
            else {
                response="";    

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

.......

private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }

【讨论】:

  • 感谢您的解决方案!
  • 谷歌糟透了。我不敢相信这里没有可靠的库或 Android API 中的 HTTP 请求包装器。
【解决方案2】:

使用Volley 怎么样?与 URLConnection 相比,这似乎是一个非常好的选择。它在请求排队方面有很多好处。

【讨论】:

    【解决方案3】:

    使用这个 httpmime-4.1-beta1.jar 试试这个代码:-

    String url = "http://www.yoursite.com/script.php";
    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost postMethod = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity();
    try 
    {
        entity.addPart("id", new StringBody("123"));
        entity.addPart("stringdata", new StringBody("AndDev is Cool!"));
        postMethod.setEntity(entity);
        HttpResponse response;
        response = client.execute(postMethod);
        String result = EntityUtils.toString(response.getEntity());
        JSONArray ja = new JSONArray(result);
        // ITERATE THROUGH AND RETRIEVE CLUB FIELDS
        int n = ja.length();
        for (int i = 0; i < n; i++) 
        {
          // GET INDIVIDUAL JSON OBJECT FROM JSON ARRAYJSONObject jo = ja.getJSONObject(i);
          // RETRIEVE EACH JSON OBJECT'S FIELDS
          String status = jo.getString("status");
          // Log.e("status",status);
        }
    }
    catch (Exception e)
    {
       e.printStackTrace();
    }
    

    【讨论】:

    • 我不想使用其他 apache lib...想使用 UrlConnection
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 2012-12-25
    • 2021-08-31
    • 2015-09-18
    相关资源
    最近更新 更多