httpclient HttpResponse response = client.execute(post);报空指针问题

HttpResponse response = client.execute(post);报空指针。

有点莫名奇妙的,client与post对话经过log与debug,都没有发现是null啊。,。。。


然后开始各种排错,常见的没加网络权限及网络访问没放在子线程中,都没有犯这样错啊。。。

最终注释掉post.setHeaders(headers);,又好了。。。(之前同一份代码在另一工程中,没问题啊。。。)

代码如下:

public static Object post(Context context,RequestVo vo,String IpAddress,String port){
		DefaultHttpClient client = new DefaultHttpClient();
		String baseUrl = "http://"+IpAddress+":"+port;
		Log.e("URL:", baseUrl.concat(context.getString(vo.requestUrl)));
		HttpPost post = new HttpPost(baseUrl.concat(context.getString(vo.requestUrl)));
		HttpParams params = new BasicHttpParams();   
	    HttpConnectionParams.setConnectionTimeout(params, 8000);   //连接超时
	    HttpConnectionParams.setSoTimeout(params, 5000);   //响应超时
		post.setParams(params);
		//post.setHeaders(headers);      //这行代码注释掉,不能给post加头
		Object obj = null;
		try {
			//设置请求参数
			if(vo.requestDataMap!=null){
				HashMap<String,String> map = vo.requestDataMap;
				ArrayList<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
				for(Map.Entry<String,String> entry:map.entrySet()){
					BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
					pairList.add(pair);
				}
				HttpEntity entity = new UrlEncodedFormEntity(pairList,Constant.CHARSET);
				post.setEntity(entity);
			}
			HttpResponse response = client.execute(post);//包含响应的状态和返回的结果==
			if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				String jsonStr = EntityUtils.toString(response.getEntity(),Constant.CHARSET);
				Log.e(NetUtil.class.getSimpleName(), jsonStr);
				try {
					obj = vo.jsonParser.parseJSON(jsonStr);//回调解析器,解析服务器返回的数据
					if(null == obj){
						JSONObject json = new JSONObject(jsonStr);
						String respCode = json.getString(Constant.RESP_CODE);
						String respDesc = json.getString(Constant.RESP_DESC);
						if(!TextUtils.isEmpty(respCode)){
							ErrorResponse errRes = new ErrorResponse();
							errRes.setRespCode(respCode);
							errRes.setRespDesc(respDesc);
							obj = errRes;
						}
					}
				} catch (JSONException e) {
					Log.e(NetUtil.class.getSimpleName(), e.getLocalizedMessage(),e);
				}
				return obj;
			}
		} catch (ClientProtocolException e) {
			Log.e(NetUtil.class.getSimpleName(), e.getLocalizedMessage(),e);
		} catch (IOException e) {
			Log.e(NetUtil.class.getSimpleName(), e.getLocalizedMessage(),e);
		}
		return null;
		
	}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
优化这段代码@PostMapping("/login") @ResponseBody @PassToken public Object login(String username,String password) throws IOException { String url="http://42.177.95.222:9202/platform/yugang/task/getToken"; HttpClient client = HttpClients.createDefault(); //默认post请求 HttpPost post = new HttpPost(url); //拼接多参数 JSONObject json = new JSONObject(); json.put("username", "渔业协会"); json.put("password", "Yuye!@#qwe"); post.addHeader("Content-type", "application/json; charset=utf-8"); post.setHeader("Accept", "application/json"); post.setEntity(new StringEntity(json.toString(), Charset.forName("utf-8"))); HttpResponse httpResponse = client.execute(post); HttpEntity entity = httpResponse.getEntity(); String s = EntityUtils.toString(entity); JSONObject jo = JSONObject.parseObject(s); String token = jo.getJSONObject("data").getString("token"); System.out.println("dsadasdasdsadasd"+token); return verify(token); } public Object verify(String token) throws IOException { String url="http://42.177.95.222:9202/platform/yugang/task/verify"; HttpClient client = HttpClients.createDefault(); //默认post请求 HttpPost post = new HttpPost(url); //拼接多参数 JSONObject json = new JSONObject(); json.put("token",token); post.addHeader("Content-type", "application/json; charset=utf-8"); post.setHeader("Accept", "application/json"); post.setEntity(new StringEntity(json.toString(), Charset.forName("utf-8"))); HttpResponse httpResponse = client.execute(post); HttpEntity entity = httpResponse.getEntity(); String s = EntityUtils.toString(entity); JSONObject jo = JSONObject.parseObject(s); return jo; }
05-27
这段代码的优化点有以下几个: 1. 将重复的代码抽取成公共方法,避免代码冗余。 2. 使用连接池管理 HttpClient 的连接,提高连接的复用率和性能。 3. 使用 try-with-resources 语句关闭 HttpClient 和 HttpEntity 对象,避免资源泄漏。 下面是代码优化后的示例: ``` private static final String BASE_URL = "http://42.177.95.222:9202/platform/yugang/task"; private CloseableHttpClient httpClient = HttpClientBuilder.create() .setMaxConnTotal(200) .setMaxConnPerRoute(100) .build(); @PostMapping("/login") @ResponseBody @PassToken public Object login(String username, String password) throws IOException { String token = getToken(); System.out.println("dsadasdasdsadasd" + token); return verify(token); } private String getToken() throws IOException { String url = BASE_URL + "/getToken"; HttpPost post = new HttpPost(url); post.addHeader("Content-type", "application/json; charset=utf-8"); post.setHeader("Accept", "application/json"); JSONObject json = new JSONObject(); json.put("username", "渔业协会"); json.put("password", "Yuye!@#qwe"); post.setEntity(new StringEntity(json.toString(), Charset.forName("utf-8"))); try (CloseableHttpResponse response = httpClient.execute(post)) { HttpEntity entity = response.getEntity(); if (entity != null) { String s = EntityUtils.toString(entity); JSONObject jo = JSONObject.parseObject(s); return jo.getJSONObject("data").getString("token"); } return null; } } private JSONObject verify(String token) throws IOException { String url = BASE_URL + "/verify"; HttpPost post = new HttpPost(url); post.addHeader("Content-type", "application/json; charset=utf-8"); post.setHeader("Accept", "application/json"); JSONObject json = new JSONObject(); json.put("token", token); post.setEntity(new StringEntity(json.toString(), Charset.forName("utf-8"))); try (CloseableHttpResponse response = httpClient.execute(post)) { HttpEntity entity = response.getEntity(); if (entity != null) { String s = EntityUtils.toString(entity); return JSONObject.parseObject(s); } return null; } } ``` 在优化后的代码中,我们将 HttpClient 对象的创建和关闭都放在了方法外部,使用连接池管理 HttpClient 的连接,提高连接的复用率和性能。同时,我们也将 getToken 和 verify 方法抽取出来,避免了代码冗余。最后,我们使用了 try-with-resources 语句来关闭 HttpClient 和 HttpEntity 对象,避免了资源泄漏。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值