出错信息: Exception in thread "main" java.lang.NullPointerException at org.apache.http.impl.client.CloseableHttpClient.determineTarget(CloseableHttpClient.java:91) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107) at com.imooc.util.WeixinUtil.doGetStr(WeixinUtil.java:35) at com.imooc.util.WeixinUtil.getAssessToken(WeixinUtil.java:80) at com.imooc.test.WeixinTest.main(WeixinTest.java:9)
WeixinTest.java:
package com.imooc.test;
import com.imooc.po.AccessToken;
import com.imooc.util.WeixinUtil;
public class WeixinTest {
public static void main(String[] args){
AccessToken token = WeixinUtil.getAccessToken();
System.out.println("票据:"+token.getToken());
System.out.println("有效时间:"+token.getExpiresIn());
}
}WeixinUtil.java:
public static JSONObject doGetStr(String url){
DefaultHttpClient httpClient = new DefaultHttpClient();
// DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet();
JSONObject jsonObject = null;
try {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity= response.getEntity();
if(entity !=null){
String result = EntityUtils.toString(entity,"UTF-8");
jsonObject = JSONObject.fromObject(result);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
/**
* post请求
* @param url
* @param outStr
* @return
*/
public static JSONObject doPostStr(String url,String outStr){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
JSONObject jsonObject = null;
try {
httpPost.setEntity(new StringEntity(outStr,"UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
String result = EntityUtils.toString(response.getEntity(),"UTF-8");
jsonObject = JSONObject.fromObject(result);
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
/**
* 获取accessToken
* @return
*/
public static AccessToken getAccessToken() {
AccessToken token = new AccessToken();
String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
JSONObject jsonObject = doGetStr(url);
if(jsonObject!=null){
token.setToken(jsonObject.getString("access_token"));
token.setExpiresIn(jsonObject.getInt("expires_in"));
}
return token;
}
}AccessToken.java:
package com.imooc.po;
public class AccessToken {
private String token;
private int expiresIn;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
}加载的jar包:
我也是报错空指针,没传参数啊,但我是跟着老师敲的啊
解决了没有 我这边也是这样
at com.imooc.util.WeixinUtil.doGetStr(WeixinUtil.java:35)
at com.imooc.util.WeixinUtil.getAssessToken(WeixinUtil.java:80)
at com.imooc.test.WeixinTest.main(WeixinTest.java:9)
错误可能发生在WeixinUtil.java:80这一行,请把这个类中59行之后的内容贴出来,这样大家可以帮助你分析