dポイントプレゼントキャンペーン実施中!

TcpClientでストリームからバイトでhttpデータを取得しましたが、
EUC-JPの文字コードのサイトだけがhtml内に本来入るはずのない数値が沢山現れます。
いっそのことWebBrowserコントロールを使ってサイトにアクセスし、DocumentTextを参照した方が手っ取り早いでしょうか?

バイトから文字列の変換はわかりましたが、文字列から文字列へ文字コードを変換する方法がわからず困っています。ご存知の方教えていただけますか?

以下、EUC-JPの時に数値が混入するサンプルです。

'---------------------------------------------------------------------------------------------------
' httpファイルを読み込む
'---------------------------------------------------------------------------------------------------
Private Sub GetHttp(ByVal host As String, ByVal port As Integer, ByVal cmd As String, ByRef retcode As Integer, ByRef http_data As String)

'TCP/IP接続を行う
Dim client As New TcpClient()
Try
client.Connect(host, port)
'ストリームを取得する
Dim stream As NetworkStream = client.GetStream()
Dim param As String = cmd + " HTTP/1.0" + ControlChars.CrLf+ControlChars.CrLf

Dim buffer() As Byte = System.Text.Encoding.ASCII.GetBytes(param)
stream.Write(buffer, 0, buffer.Length)

Dim sb As New System.Text.StringBuilder()

Dim len As Integer
http_data = ""
Dim bytData() As Byte = New Byte(1048576) {} '1MB
Dim strCharset As String = ""

'すべて受信する
Dim cnt As Integer
For cnt = 1 To 1000
'受信
len = stream.Read(bytData, 0, bytData.Length) 'バッファサイズを与えて、受信サイズを得る
sb.Append(Encoding.GetEncoding("utf-8").GetString(bytData, 0, len)) 'utf-8
If Not stream.DataAvailable Then '受信キューにデータがある場合はTrue
Exit For
End If

Next

'正常に受信できた場合
http_data = sb.ToString
retcode = 0

Catch ex As Exception
retcode = -1
http_data = ""
Finally
client.Close()
End Try

End Sub

'-----
Dim host As String = "ホスト名"
Dim port As Integer = 80
Dim cmd As String = "GET /index.html"

'戻り値
Dim retcode As Integer
Dim http_data As String = ""
Dim charset As String = ""

Try
GetHttp(host, port, cmd, retcode, http_data)
Catch ex As Exception
MessageBox.Show(ex.Message, "エラーです。")
End Try

A 回答 (1件)

受信データを文字列変換する際のエンコーダをEUC-JPにすればいいのでは


sb.Append(Encoding.GetEncoding("EUC-JP").GetString(bytData, 0, len)) 'utf-8
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!