具有特殊字符的Android http帖子

时间:2014-12-29 16:51:42

标签: android http utf-8 special-characters

我的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();
}

2 个答案:

答案 0 :(得分:0)

我认为因为setonclikListener是一个函数/监听器而且i变量是本地变量而你没有将这个变量作为参数传递,你可以把这个变量作为属性,在类顶部使用public int i = x / p>

答案 1 :(得分:0)

首先,变量i超出了侦听器的范围,因此您无法使用它。

其次,请记住在for循环完成后将调用click侦听器,因此使用变量i是不可能的(它不再存在)。但是,当您声明一个final变量时,它将始终在侦听器中可用。但你无法改变它的价值。

for(int i=0;i<end;i++)
{   
    //bilder
    ImageView replace_img= new ImageView(this);
    replace_img.setImageResource(R.drawable.image_replace);
    RelativeLayout.LayoutParams tmp= new RelativeLayout.LayoutParams(250,250);
    newImg.add(replace_img);                
    ImageView v=  newImg.get(i);
    v.setId(i+1);

    // Set the final int that will be available in inner classes
    final int myInt = i;

    v.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View vi) {            
            vi.setOnClickListener(new View.OnClickListener() 
            { 
                @Override
                public void onClick(View v) 
                { 
                    // "myInt" is still usable here, however "i" is not
                    Intent o = new Intent(getBaseContext(), Edit_post2.class);
                    o.putExtra("POST_NR", myInt);
                    Post_list.this.startActivity(o); 
                }
            });
        }
    });
}