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做怎么的相应处理?
如果能给出直接的代码让我研究学习那就最好啦^-^
c# .net httpentity httpclient 转换
黄昏的颂歌
9 years, 5 months ago
Answers
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;
大致有这么一个对应关系。
巧克力脆皮猪蹄
answered 9 years, 5 months ago