我的php网站正在回应“härärdu/xvårisikte”,在我的Chrome浏览器中显示为“härärdu/xvårisikte”。 但是当我在我的java / android应用程序中使用httppost读取它时,所有特殊字符(åäö)都显示为问号。我的虚拟主机服务使用UtF-8。有没有办法转换我的字符串? 这是我的代码:
StringBuffer response = new StringBuffer();
try {
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpPost post = new HttpPost("my.php");
try {
post.setHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
MultipartEntityBuilder builder = MultipartEntityBuilder
.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
final HttpEntity entity = builder.build();
post.setEntity((HttpEntity) entity);
//builder.addTextBody("rubrik_nr", all_rubrik, ContentType.TEXT_PLAIN);
HttpResponse resp = defaultClient.execute(post);
}catch(Exception E){
}
// Execute the request in the client
HttpResponse httpResponse = defaultClient
.execute(post);
BufferedReader in = new BufferedReader(new InputStreamReader(
httpResponse.getEntity().getContent(),"UTF-8"));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.d("DEBUG", "response: " + response.toString());
} catch (IOException e) {
Log.d("DEBUG", "j " + response.toString());
e.printStackTrace();
}
return response.toString();
}
答案 0 :(得分:1)
我会尝试给您一个示例代码,但如果您可以准确地写出您遇到问题的地方以及您不了解的内容,那将会非常有用。 您将需要AsyncTask进行网络操作。试试以下内容:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncConnection().execute();
}
// This is the code for async task.
public class AsyncConnection extends AsyncTask<Void, Void, String> {
@Override
protected void onPostExecute(String result) {
// you can use your result string here
}
@Override
protected String doInBackground(Void... params) {
StringBuffer response = new StringBuffer();
try {
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("URL");
// Execute the request in the client
HttpResponse httpResponse = defaultClient
.execute(httpGetRequest);
BufferedReader in = new BufferedReader(new InputStreamReader(
httpResponse.getEntity().getContent()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.d("DEBUG", "response: " + response.toString());
} catch (IOException e) {
Log.d("DEBUG", "j " + response.toString());
e.printStackTrace();
}
return response.toString();
}
}
}