小程序获取openid,报java.lang.NullPointerException错误
看了下代码,参数都有传过去,实在找不出哪里有错
public static Map<String,Object> login(String code) throws Exception{
if(code==null||code.equals("")) {
throw new Exception("小程序登录凭证不能为空");
}
//返回结果
Map<String,Object> ret=new HashMap<String,Object>();
Map<String,String> params=new HashMap<String,String>();
params.put("grant_type", grant_type);
params.put("appid",appid);
params.put("secret",app_secret);
params.put("js_code", code);
//调用获取access_token接口
String result=httpPost(access_token_url,params);
System.out.println(result);
//根据请求结果判定,是否验证成功
JSONObject obj=JSONObject.fromObject(result);
if(obj!=null) {
Object errCode=obj.get("errcode");
if(errCode!=null) {
throw new Exception("errCode:"+errCode);
}else {
Object session_key=obj.get("session_key");//会话密钥
Object openid=obj.get("openid");//唯一标识
ret.put("session_key", session_key);
ret.put("openid", openid);
}
}
return ret;
}
public static String httpGet(String url) {
DefaultHttpClient httpclient=new DefaultHttpClient();
String body=null;
HttpGet get=new HttpGet(url);
body=invoke(httpclient,get);
httpclient.getConnectionManager().shutdown();
return body;
}
public static String httpPost(String url,Map<String,String> params) {
System.out.println("httpPost:"+params+"url:"+url);
DefaultHttpClient httpclient=new DefaultHttpClient();
String body=null;
HttpPost post=postForm(url,params);
body=invoke(httpclient,post);
httpclient.getConnectionManager();
return body;
}
private static HttpPost postForm(String url,Map<String,String>params) {
HttpPost httppost=new HttpPost();
System.out.println(httppost);
List<NameValuePair> nvps=new ArrayList<NameValuePair>();
for(String key:params.keySet()) {
if(key!=null) {
nvps.add(new BasicNameValuePair(key,params.get(key)));
}
}
try {
httppost.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}
return httppost;
}
private static String invoke(DefaultHttpClient httpclient,HttpUriRequest httppost) {
HttpResponse response=sendRequest(httpclient,httppost);
String body=parseResponse(response);
return body;
}
private static HttpResponse sendRequest(DefaultHttpClient httpclient,HttpUriRequest httppost) {
HttpResponse response=null;
try {
response=httpclient.execute(httppost);
System.out.println(response);
}catch(ClientProtocolException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
return response;
}
private static String parseResponse(HttpResponse response) {
HttpEntity entity=response.getEntity();
String charset=EntityUtils.getContentCharSet(entity);
charset=StringUtils.isEmpty(charset)?"utf-8":charset;
String body=null;
try {
body=EntityUtils.toString(entity,charset);
}catch(ParseException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
return body;
}
```求好心人帮忙看看代码哪里有错T_T 感激不尽