Android 訪問網頁

public String sendRequest(String requestPage, Map map) {
        String strResult = "";

        HttpPost httpRequest = new HttpPost(requestPage);
        List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
        if (!map.isEmpty()) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                postData.add(new BasicNameValuePair(entry.getKey(), entry
                        .getValue()));
            }
        }

        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData,
                    HTTP.UTF_8);
            httpRequest.setEntity(entity);
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            return null;
        }

        try {
            DefaultHttpClient dhc = new DefaultHttpClient();
            // 設置超時
            dhc.getParams().setParameter(
                    CoreConnectionPNames.CONNECTION_TIMEOUT,
                    AppConstant.Constant.TimeOut_Time);
            dhc.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                    AppConstant.Constant.TimeOut_Time);
            // 發送
            HttpResponse httpResponse = dhc.execute(httpRequest);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                // gb2312要和服務器上一至以避免亂碼
                strResult = EntityUtils.toString(httpResponse.getEntity(),
                        "gb2312");
            } else {
                strResult = AppConstant.Constant.Connect_Fail;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strResult;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章