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

我需要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学习者快速成长!