一、利用httpclient来字符串参数(url是第三方接口,不带参数,如:http://192.168.16.200:8081/faceInfo/list,param是url后面所要带的参数)
public static JSONObject getHttpResponseJson(String url,Map<String,String> param){ CloseableHttpClient httpclient = null; CloseableHttpResponse response = null; JSONObject jsonObject = null; try { //请求发起客户端 httpclient = HttpClients.createDefault(); //参数集合 List postParams = new ArrayList(); //遍历参数并添加到集合 for(Map.Entry<String, String> entry:param.entrySet()){ postParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } //通过post方式访问 HttpPost post = new HttpPost(url); HttpEntity paramEntity = new UrlEncodedFormEntity(postParams,"UTF-8"); post.setEntity(paramEntity); response = httpclient.execute(post); HttpEntity valueEntity = response.getEntity(); String content = EntityUtils.toString(valueEntity); jsonObject = JSONObject.fromObject(content); return jsonObject; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if(httpclient != null){ try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } if(response != null){ try { response.close(); } catch (IOException e) { e.printStackTrace(); } } } return jsonObject; }
二、利用httpclient来同时上传文件和其他字符串参数(postUrl)
public static String getHttpResponseString(String postUrl,Map<String,String> filePathParam,Map<String,String> param){ //1:创建一个httpclient对象 HttpClient httpclient = new DefaultHttpClient(); Charset charset = Charset.forName("UTF-8");//设置编码 try { //2:创建http的发送方式对象,是GET还是post HttpPost httppost = new HttpPost(postUrl); //3:创建要发送的实体,就是key-value的这种结构,借助于这个类,可以实现文件和参数同时上传 MultipartEntity reqEntity = new MultipartEntity(); //遍历图片并添加到MultipartEntity实体中 for(Map.Entry<String, String> entry:filePathParam.entrySet()){ FileBody fileContent = new FileBody(new File(entry.getValue())); reqEntity.addPart(entry.getKey(),fileContent); } //遍历参数并添加到MultipartEntity实体中 for(Map.Entry<String, String> entry:param.entrySet()){ StringBody content = new StringBody(entry.getValue(),charset); reqEntity.addPart(entry.getKey(), content); } httppost.setEntity(reqEntity); //4:执行httppost对象,从而获得信息 HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); //获得返回来的信息,转化为字符串string String resString = EntityUtils.toString(resEntity); return resString; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {} } return null; }
原文地址:https://www.cnblogs.com/xuegu/p/8490815.html
时间: 2024-11-29 08:07:35