u012536005
小横
2015-05-20 08:52

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

10
  • 接口
  • 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;
}

}


  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

8条回答