Android網絡常用的請求---HttpURLConnection和HttpClient

<span style="font-size:18px;">/**
     * method one:
     * */
    public static void sendHttpRequest(final String urlStr, final HttpCallBackListener listenser) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(urlStr);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);

                    InputStream in = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }

                    if (listenser != null) {
                        listenser.onfinish(response.toString());
                    }

                } catch (Exception e) {
                    if (listenser != null) {
                        listenser.onError(e);
                    }
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    public interface HttpCallBackListener {
        void onfinish(String response);

        void onError(Exception e);
    }

    /**
     * method two: HttpClient--HttpGet
     * */
    public String cookieStr = "";

    public String sendRequestWithHttpClient(final String urlStr) {
        String response = null;
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(urlStr);
        httpGet.setHeader("Cookie", cookieStr);
        HttpResponse httpResponse;
        try {
            httpResponse = httpClient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = httpResponse.getEntity();
                response = EntityUtils.toString(entity, "utf-8");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return response;
    }

    /**
     * method two: HttpClient--HttpPost
     * requestBody:"<Result><UserName>MeiMei</UserName></Result>"
     */
    public synchronized String post(String requestBody, URI url) {
        String requestResult = null;
        HttpPost httpRequest = new HttpPost();
        httpRequest.setURI(url);
        httpRequest.setHeader("Cookie", cookieStr);

        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("inputXml", requestBody));
            httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                Header[] headers = httpResponse.getAllHeaders();
                for (Header header : headers) {
                    if ("Set-Cookie".equals(header.getName())) {
                        String temp = header.getValue();
                        int index = temp.indexOf("Version=");
                        cookieStr += temp.substring(0, index);
                    }
                }
                requestResult = EntityUtils.toString(httpResponse.getEntity());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return requestResult;
    }
</span>
<span style="font-size:18px;">
</span>
<span style="font-size:18px;">以上是平時常用的http請求,在這裏做了一下小結,平時項目中可以根據需要來選擇使用。</span>
<span style="font-size:18px;">
</span>
<span style="font-size:18px;">
</span>
<span style="font-size:18px;">
</span>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章