java - 如何从 HttpClient 切换到 HttpUrlConnection?

标签 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 代码

安卓代码

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;
    }

这是我的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++;
    }

}

最佳答案

当我阅读 already mentioned Google post关于在较新版本的 Android 中执行 HTTP 请求的最佳实践,我以为有人在开玩笑。 HttpURLConnection 与几乎所有其他与 HTTP 服务器通信的方式(除了直接 Socket 通信)相比,使用起来真是一场噩梦。

我没有找到一个非常精简的 Android 库来完成繁重的工作,所以我自己写了一个。您可以在 DavidWebb 找到它包括 a list of alternative libraries这是我在开发库后(不幸地)发现的。

您的代码或多或少看起来像这样:

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"));
}

关于java - 如何从 HttpClient 切换到 HttpUrlConnection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26898667/

相关文章:

java - java中的问号是什么意思?

c# - 什么是 ASP.net 项目中的 Servlet(在 tomcat 中扩展 HttpServlet 的 Java 类)?

javascript - 将多行字符串从数据库传递到javascript变量

oracle - 浏览器关闭时防止单用户多登录

java - 无法创建 PoolableConnectionFactory(未知系统变量 'language')

java - 我可以在实例化时设置一个带有期望(验证)的 Mockito 模拟吗?

java - 加载 spring camel 上下文时出错(类型不匹配)

java - ViewPager2#onpageselect StackOverflowError

Android - 每天早上 5 点运行服务的闹钟管理器

java - 将对象从 Activity 传递到 Service,该对象不能实现 Serialized 或 Parcelable