如何从HttpClient切换到HttpUrlConnection?

Bha*_*nki 4 java android servlets httpurlconnection apache-httpclient-4.x

我正在创建一个Android应用程序,我通过HttpClient将数据从Android应用程序发送到servlet.我使用HttpPost方法.

我在Android开发者网站上读到Apache HttpClient库在Android Froyo 2.2中有一些错误,毕竟使用HttpUrlConnection而不是HttpPost是一个好习惯.所以我想将我的HttpPost代码转换为HttpUrlConnectio,但不知道如何.

我在这里发布我的Android代码以及servlet代码

Android代码

private String postData(String valueIWantToSend[]) 
    {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        try 
        {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("param1",valueIWantToSend[0]));
            nameValuePairs.add(new BasicNameValuePair("param2", valueIWantToSend[1]));
            nameValuePairs.add(new BasicNameValuePair("param3", valueIWantToSend[2]));
            nameValuePairs.add(new BasicNameValuePair("param4", valueIWantToSend[3]));
            nameValuePairs.add(new BasicNameValuePair("param5", valueIWantToSend[4]));
            nameValuePairs.add(new BasicNameValuePair("param6", valueIWantToSend[5]));
            nameValuePairs.add(new BasicNameValuePair("param7", valueIWantToSend[6]));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            /* execute */
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity rp = response.getEntity();

            //origresponseText=readContent(response);
        }
        catch (ClientProtocolException e) 
        {
            // TODO Auto-generated catch block
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
        }
        return null;
    }
Run Code Online (Sandbox Code Playgroud)

这是我的servlet代码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html");
    ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
    Enumeration paramNames = request.getParameterNames();
    String params[] = new String[7];
    int i=0;

    while(paramNames.hasMoreElements())
    {
        String paramName = (String) paramNames.nextElement();
        System.out.println(paramName);


        String[] paramValues = request.getParameterValues(paramName);
        params[i] = paramValues[0];

        System.out.println(params[i]);

        i++;
    }

}
Run Code Online (Sandbox Code Playgroud)

hgo*_*ebl 5

当我阅读已经提到的关于在新版Android中执行HTTP请求的最佳做法的Google帖子时,我以为有人在开玩笑.HttpURLConnection与几乎任何其他与HTTP服务器通信的方式(除了直接的Socket通信)相比,使用它真的是一场噩梦.

我没有找到一个非常纤薄的Android库来完成繁重的工作,所以我写了自己的.你可以在DavidWebb找到它,包括我在开发库后发现的(遗憾的是)替代库的列表.

你的代码看起来或多或少是这样的:

public void testPostToUrl() throws Exception {
    String[] values = new String[3];

    Webb webb = Webb.create();
    Response<String> response = webb
            .post("http://www.example.com/abc.php")
            .param("param1", values[0])
            .param("param2", values[1])
            .param("param3", values[2])
            .asString();

    assertEquals(200, response.getStatusCode());
    assertNotNull(response.getBody());
    assertTrue(response.getBody().contains("my expected result"));
}

public void testPostToUrlShorter() throws Exception {
    String[] values = new String[3];

    Webb webb = Webb.create();
    String result = webb
            .post("http://www.example.com/abc.php")
            .param("param1", values[0])
            .param("param2", values[1])
            .param("param3", values[2])
            .ensureSuccess()
            .asString()
            .getBody();

    assertTrue(result.contains("my expected result"));
}
Run Code Online (Sandbox Code Playgroud)


Jef*_*xon 1

你绝对应该使用HttpUrlConnection

对于 Gingerbread 甚至更好,HttpURLConnection 是最佳选择...新应用程序应该使用 HttpURLConnection...

——谷歌(约 2011 年)

然而,仅仅“切换”并没有简单的方法。API 完全不同。您将不得不重写您的网络代码。文档以及 SDK 示例应用程序中都有关于如何提交 GET 和 POST 请求的完美示例。