2013-10-04 69 views
0

我想发送一个简单的HTTP POST请求到Web服务并阅读响应。我需要在.NET项目中执行此操作,但通话始终失败。我测试过在Java中调用相同的Web服务,并且完全没有问题。Http POST请求成功在Java中,但在C#中失败

这里是我的C#代码:

HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "web service URI"); 


     string json = "some json input"; 
     requestMessage.Content = new StringContent(json, Encoding.UTF8, "application/json");    
     HttpClient httpClient = new HttpClient();  
     httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)"); 
     httpClient.DefaultRequestHeaders.Add("Accept-Language", "en"); 
     httpClient.DefaultRequestHeaders.Add("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*");                              
     httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate"); 
     httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); 
     httpClient.DefaultRequestHeaders.Add("Connection", "Keep-Alive"); 
     httpClient.DefaultRequestHeaders.ExpectContinue = false; 

     try 
     {    
      Task<HttpResponseMessage> httpRequest = httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead 
       , CancellationToken.None); 

      HttpResponseMessage httpResponse = httpRequest.Result; 
      HttpStatusCode statusCode = httpResponse.StatusCode; 
      HttpContent responseContent = httpResponse.Content; 
      if (responseContent != null) 
      { 
       Task<string> stringContentTask = responseContent.ReadAsStringAsync(); 
       string stringContent = stringContentTask.Result; 
       return stringContent; 
      } 
      else 
      { 
       throw new Exception("Response content is null."); 
      } 
     } 
     catch (AggregateException ae) 
     { 
      List<Exception> innerExceptions = ae.InnerExceptions.ToList(); 
      StringBuilder sb = new StringBuilder(); 
      foreach (Exception e in innerExceptions) 
      { 
       sb.Append(e.Message).Append(Environment.NewLine); 
       if (e.InnerException != null) 
       { 
        sb.Append(e.InnerException.Message).Append(Environment.NewLine); 
       } 
      } 
      Console.WriteLine(sb.ToString()); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
     } 

当我打电话httpRequest.Result的代码失败。最终的异常消息如下:

“无法从传输连接读取数据:连接已关闭。”

但是,当我在Java中尝试相同时,它的工作原理完美。这是我的Java代码:

String url = "web service URI"; 
     URL obj = new URL(url); 
     HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)"); 
     connection.setRequestProperty("Accept-Language", "en"); 
     connection.setRequestProperty("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*"); 
     connection.setRequestProperty("Accept-Encoding", "gzip, deflate"); 
     connection.setRequestProperty("Content-Type", "application/json"); 
     connection.setRequestProperty("Cache-Control", "no-cache"); 
     connection.setRequestProperty("Connection", "Close"); 
     String content = "some json"; 
     connection.setDoOutput(true); 
     DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); 
     wr.writeBytes(content); 
     wr.flush(); 
     wr.close(); 

     int responseCode = connection.getResponseCode(); 
     System.out.println("\nSending 'POST' request to URL : " + url); 
     System.out.println("Post parameters : " + content); 
     System.out.println("Response Code : " + responseCode); 

     BufferedReader in = new BufferedReader(
       new InputStreamReader(connection.getInputStream())); 
     String inputLine; 
     StringBuilder response = new StringBuilder(); 

     while ((inputLine = in.readLine()) != null) 
     { 
      response.append(inputLine); 
     } 
     in.close(); 

     //print result 
     System.out.println(response.toString()); 

对于C#的一部分我在.NET测试其他HTTP相关对象:HttpWebRequest和WebClient的,只能得到同样的异常信息。

我怀疑.NET对象添加某种类型的标题或必须禁用的默认设置,但我不知道它是什么。

FYI:
- Java代码的工程,即使我删除所有调用setRequestProperty调用,因此代码没有经过明确设置“用户代理”,“接受语言”等 - 网络服务设置直到通信结束后立即关闭连接,即没有保持活动状态。我似乎记得,这个功能是.NET Web客户端对象“不喜欢的”,但我不会在这上面打赌。 - 您会注意到我在C#中将ExpectContinue设置为false,但不是在Java中。在Java中,显然没有必要,而我不得不在其他C#项目中将其关闭,以使调用正常工作。我测试将其设置为true,结果没有任何差异。

欢迎任何建议。我无法控制Web服务设置,因此请不要提出任何需要此类更改的建议。

感谢, 安德拉什

+0

你试过了吗? – Aravind

+0

您是否使用我的回答进行了检查 – Aravind

+0

尝试使用没有缓存控制标头的相同代码 – pamidur

回答

0

我建议不增加的连接头。首先,与HttpClient的,如果你要问的服务器关闭请求后,连接你会做

httpClient.DefaultRequestHeaders.ConnectionClose = true; 

HTTP 1.1用途保活在默认情况下,所以没有需要发送的报头。如果服务器返回Connection: close那么客户端应该处理得很好。

HttpClient确实有点不安,当你开始搞乱它想要控制的标题时。

+0

感谢您的建议。我删除了所有头文件声明并添加了connectionclose = true位,但我仍然不幸遇到了相同的异常。 – Andras

-1

试试这个

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("Your URL"); 
     byte[] data = Encoding.UTF8.GetBytes("Post Input"); 
     request.Method = "POST"; 
     request.Accept = "application/json"; //you can set application/xml 
     request.ContentType = "application/json";// you can set application/xml 
     Stream dataStream = request.GetRequestStream(); 
     dataStream.Write(data, 0, data.Length); 
     dataStream.Close(); 
     HttpWebResponse resp = (HttpWebResponse)request.GetResponse(); 
     StreamReader result = new StreamReader(resp.GetResponseStream()); 
     if(result !=null) 
     { 
     if(!string.IsNullorEmpty(result.ReadToEnd().ToString())) 
     { 
      MessageBox.Show(result.ReadToEnd().ToString()); 
     } 
     } 
0

你可能想尝试提琴手Web调试代理。它可能有助于查找HTTP流量的差异(fiddler2.com)。

相关问题