.net - Java封装httpGet方法和C#封装httpGet入门级别的问题 | 代码转化:Java -》 C#
巴扎黑
巴扎黑 2017-04-17 14:50:55
0
3
346

我需要c# 用httpclient实现的例子。 system.net.http.

 //public static HttpClientResult httpGet(string url, IDictionary<string, string> headMap)
        public static string httpGet(string url, IDictionary<string, string> headMap)
        {
            string response = "";
            HttpGet httpGet = null;
            CloseableHttpResponse ht = null;
            try
            {
                httpGet = new HttpGet(url);

                if (headMap != null && headMap.Count > 0)
                {
                    foreach (string name in headMap.Keys)
                    {
                        httpGet.addHeader(name, headMap[name]);
                    }
                }

                CloseableHttpClient hc = HttpClients.createDefault();
                RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build(); //设置请求和传输超时时间
                httpGet.Config = requestConfig;
                ht = hc.execute(httpGet);
                 
                HttpEntity het = ht.Entity;
                InputStream @is = het.Content;
                BufferedReader br = new BufferedReader(new InputStreamReader(@is, "utf8"));
                string readLine;
                while ((readLine = br.readLine()) != null)
                {
                    response = response + readLine;
                }
                @is.close();
                br.close();
                int status = ht.StatusLine.StatusCode;
                //return new HttpClientResult(status, response);
                return null;
            }
            catch (Exception e)
            {
                throw new HttpClientException(e);
            }
            finally
            {
                if (httpGet != null)
                {
                    httpGet.releaseConnection();
                } 
                if (ht != null)
                {
                    try
                    {
                        ht.close();
                    }
                    catch (IOException)
                    {
                    }
                }
            }
        }

这是一段java里封装httpget的方法,有没有人能帮忙翻译成C#相应的代码,让我作为示例代码,学习一下。我是做java的,对C#非常不熟。

大神辛苦了,这个问题对大神来说肯定很简单,只要核心代码翻译一下就好,异常啥的就不要啦,最好C#流的常用类也能指点下

巴扎黑
巴扎黑

人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!