我正在尝试将以前编写的.net winform应用程序从vb转换为c#,并且遇到了Web发送功能的麻烦。如何将其转换为C#?
Public Shared Function Send(p_ipAddress As String, p_action As String, p_page As String, p_body As String, p_filePath As String) As String
Dim objHttp = CreateObject("MSXML2.ServerXMLHTTP")
'objHttp.setTimeouts(1000, 1000, 1000, 1000) '-- Timeout
objHttp.Open(p_action, sUrl, False)
If t_fileContent.Length > 0 Then
objHttp.setRequestHeader("Content-Type", "multipart/form-data; boundary=" & t_multipart_boundary)
Else
t_fileContent.Append(p_body)
objHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
End If
objHttp.Send(t_fileContent.ToString())
If objHttp.Status = 200 Then
Return objHttp.responseText
End If
Return ""
End Function
HTTP对象是我在转换为c#时遇到的问题。我不知道是否需要使用http客户端,http Web请求,对于Web通话我还是很陌生。
编辑,我已将代码缩短为我不确定的地方,删除了绒毛。
答案 0 :(得分:0)
尝试一下:
public static string Send(string p_ipAddress, string p_action, string p_page, string p_body, string p_filePath)
{
dynamic objHttp = Microsoft.VisualBasic.Interaction.CreateObject("MSXML2.ServerXMLHTTP");
// objHttp.setTimeouts(1000, 1000, 1000, 1000) '-- Timeout
objHttp.Open(p_action, sUrl, false);
if (t_fileContent.Length > 0)
objHttp.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + t_multipart_boundary);
else
{
t_fileContent.Append(p_body);
objHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
objHttp.Send(t_fileContent.ToString());
if (objHttp.Status == 200)
return objHttp.responseText;
return "";
}
您必须添加对Microsoft.VisualBasic.dll
的引用。
但是有适当的.NET类可以处理通过HTTP发送的消息。最好使用它们重写。
答案 1 :(得分:0)
您不必使用Microsoft.VisualBasic.dll-有一种“核心” .NET方法可以做到这一点:
public static string Send(string p_ipAddress, string p_action, string p_page, string p_body, string p_filePath)
{
dynamic objHttp = System.Activator.CreateInstance(System.Type.GetTypeFromProgID("MSXML2.ServerXMLHTTP"));
objHttp.Open(p_action, sUrl, false);
if (t_fileContent.Length > 0)
objHttp.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + t_multipart_boundary);
else
{
t_fileContent.Append(p_body);
objHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
objHttp.Send(t_fileContent.ToString());
if (objHttp.Status == 200)
return objHttp.responseText;
return "";
}