我有一个c#WPF应用程序,它向php站点发送一个POST请求。 该站点托管在Debian上运行的apache服务器上。
我的问题是发送像äöüß这样的字符,我认为这些字符编码不正确,因为如果我直接打开php网站就没有那些字符而是符号。
我已经尝试过将字符集设置为utf-8。 我忘记了什么吗?
以下是一些代码:
var url = "http://internalServer/input.php"
using (var client = await Login())
{
if (client == null) return false;
foreach (var item in day.Workitems)
{
if (item.IsSynced) continue;
try
{
var syncedText = item.Description;
if (!string.IsNullOrEmpty(item.Notes))
{
foreach (var line in item.Notes.Split(new [] {"\r\n"}, StringSplitOptions.RemoveEmptyEntries))
{
if (!string.IsNullOrEmpty(syncedText)) syncedText += ", ";
syncedText += line;
}
}
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("Ticket", item.Nr),
new KeyValuePair<string, string>("Text", syncedText)
});
await DoRequest(client, url, content);
}
catch (Exception)
{
return false;
}
}
}
return true;
}
private async Task<string> DoRequest(HttpClient client, string url, HttpContent content = null)
{
var request = new HttpRequestMessage(content == null ? HttpMethod.Get : HttpMethod.Post, url);
if (content != null)
{
request.Content = content;
}
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
答案 0 :(得分:0)
在C#中:尝试使用base64进行编码。见.netfiddle
using System;
public class Program
{
public static void Main()
{
byte[] encbuff = System.Text.Encoding.UTF8.GetBytes("äöüß");
string syncedText = Convert.ToBase64String(encbuff);
Console.WriteLine(syncedText); // you get "w6TDtsO8w58="
}
}
在PHP中:强制执行utf-8
<?php
$str = $_REQUEST['Text']; // "w6TDtsO8w58="
echo base64_decode($str); // you get "äöüß"
?>
如果你不想在C#端改变任何东西,那么试试这个
<?php
// you may want to detect the encoding of the request string
$encoding = mb_detect_encoding($str,"UTF-8,ISO-8859-1,ISO-8859-2,windows-1250");
if( $encoding == "UTF-8" ) {
echo utf8_decode($str);
// do something ...
}
else {
// if encoded with charset windows-1250, ISO-8859-2, ISO-8859-1
// e.g, $str = "Zusammenf%FChrung"; // %FC = ü
echo mb_convert_encoding(urldecode($str), "utf-8", "ISO-8859-2");
// you get "Zusammenführung" as utf-8
}
?>
OR
<?php
/*
* if your encoding is limited to a specific charset,
* you shall try changing php header as below.
*/
header('Content-Type: charset=ISO-8859-2');
echo urldecode("Zusammenf%FChrung");
// Note: insert the header() function before generating any content
?>