开发者社区> 问答> 正文

解析微信接口返回的json 中文昵称为乱码 怎么回事

package Htttp;
import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.HttpURLConnection;
 import java.net.URL;
import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
public class HttpUtils_touxiang {
public HttpUtils_touxiang() {
}
public static Touxiang getJsonContent(String url_path){


        try {
            URL url = new URL(url_path);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setConnectTimeout(3000);
            connection.setRequestMethod("GET");

            connection.setDoInput(true);

            int code = connection.getResponseCode();
            if(code ==200){
            return changeInputStream(connection.getInputStream());


            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



    return null;

}

private static Touxiang changeInputStream(InputStream inputStream) {
    // TODO Auto-generated method stub
    String jsonString = "";
    String nickname = null;
    String headimgurl =null;
    Touxiang touxiang = null;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    int len = 0;
    byte[] data = new byte[1024];
    try {
        while((len = inputStream.read(data))!=-1){

            outputStream.write(data,0,len);
        }
        jsonString = new String(outputStream.toByteArray());
        //到这里已经是乱码了
        System.out.println("先前返回的是:"+jsonString);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    JSONObject jsonObject;
    try {
        jsonObject = new JSONObject(jsonString);
        System.out.println("返回的是:"+jsonObject);
        nickname = jsonObject.getString("nickname").toString();
        headimgurl = jsonObject.getString("headimgurl");


        touxiang = new Touxiang();
        touxiang.setHeadimgurl(headimgurl);
        touxiang.setNickname(nickname);
        System.out.println("你的昵称是:"+nickname);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    return touxiang;
}
}

展开
收起
杨冬芳 2016-07-05 10:24:03 6382 0
1 条回答
写回答
取消 提交回答
  • IT从业
     jsonString = new String(outputStream.toByteArray());
            //到这里已经是乱码了
            System.out.println("先前返回的是:"+jsonString);
    
    改成
    jsonString = new String(outputStream.toByteArray(),"UTF-8");//微信接口是UTF-8格式的。
            //到这里已经是乱码了
            System.out.println("先前返回的是:"+jsonString);
    2019-07-17 19:51:13
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
神龙云服务器产品及技术深度解析 立即下载
弹性创造价值:基于ECS的最佳性价比实践解析 立即下载
又快又稳:阿里云下一代虚拟交换机解析 立即下载

相关镜像