C# .net Java httpclient HttpEntity 流读取 相关问题

Java httpclient 用如下HttpClient加流操作的方式获取response的内容

HttpGet httpGet =new HttpGet("http://www.baidu.com");
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity !=null) {
    InputStream instream = entity.getContent();
    int byteOne = instream.read();
    int byteTwo = instream.read();
    // Do not need the rest
    httpGet.abort();
}

在.net httpclient应使用哪些api做怎么的相应处理?
如果能给出直接的代码让我研究学习那就最好啦^-^

阅读 5.8k
1 个回答
  public static HttpClientResult httpGet(string url, IDictionary<string, string> headMap)
        {
            string response = "";
     
            try
            {
                HttpClient hc = new HttpClient();
                hc.Timeout = new System.TimeSpan(300);

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

                var getTask =  hc.GetAsync(new Uri(url));
                HttpResponseMessage responseM = hc.GetAsync(new Uri(url)).Result;

                Stream instream = responseM.Content.ReadAsStreamAsync().Result;
                BufferedStream bfs = new BufferedStream(instream);
                byte[] buffer = new byte[1024];
                StringBuilder sb = new StringBuilder();
                while (bfs.Read(buffer, 0, buffer.Length) > 0)
                {
                    sb.Append(Encoding.GetEncoding("UTF-8").GetString(buffer));
                }
                response = sb.ToString();

                bfs.Flush();
                bfs.Close();
                instream.Close();

                int statusCode = (int)responseM.StatusCode;
                return new HttpClientResult(statusCode, response);
            }
            catch (HttpRequestException e)
            {
                throw new HttpRequestException("HttpRequestException");
            }
            finally
            {
               
            }
        }

HttpGet ----> var getTask = hc.GetAsync(new Uri(url));
HttpResponse --> HttpResponseMessage responseM = hc.GetAsync(new Uri(url)).Result;
大致有这么一个对应关系。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进