How to switch from HttpClient to HttpUrlConnection?

前端 未结 3 813
臣服心动
臣服心动 2020-12-11 06:10

I am creating an Android application and I send data from Android application to servlet through HttpClient. I use HttpPost method.

I read in Android developer site

3条回答
  •  轮回少年
    2020-12-11 06:53

    When I read the already mentioned Google post about best practices doing HTTP requests in newer versions of Android, I thought somebody was kidding me. HttpURLConnection is really a nightmare to use, compared to almost any other way to communicate with HTTP servers (apart from direct Socket communication).

    I didn't find a really slim library for Android to do the heavy lifting, so I wrote my own. You can find it at DavidWebb including a list of alternative libraries which I found (unfortunately) after developing the library.

    Your code would look more or less like this:

    public void testPostToUrl() throws Exception {
        String[] values = new String[3];
    
        Webb webb = Webb.create();
        Response 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"));
    }
    

提交回复
热议问题