get请求
String url = "http://XXXX"; JSONObject json = new JSONObject(); CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse responses = null; String resultUrl = "";//接收请求返回的结果 try { String urlName = url + "&"+"MobNum="+MobNum + "&UserPackage="+productCode; HttpGet httpget = new HttpGet(urlName); //认证token httpget.addHeader("Authorization", json.toString()); httpget.addHeader("BipCode", BipCode); httpget.addHeader("ActivityCode", ActivityCode); httpget.addHeader("OrderId", LlyOrder.getOrderNo()); httpget.addHeader("ProductID", prodid); httpget.addHeader("content-Type", "application/json;charset=utf-8"); //发送httpget请求 responses = httpclient.execute(httpget); int result =responses.getStatusLine().getStatusCode(); //判断 if (result== HttpStatus.SC_OK){ resultUrl = EntityUtils.toString(responses.getEntity(),"utf-8"); } } catch (Exception e) { e.printStackTrace(); } // 使用finally块来关闭输入流 finally { // 6. 释放资源 try { responses.close(); httpclient.close(); } catch (IOException e) { e.printStackTrace(); } }
post请求
JSONObject jsonObject = new JSONObject(); JSONObject json = new JSONObject(); // 1. 创建HttpClient对象 CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 2. 创建HttpPost对象 HttpPost post = new HttpPost("http://XXXX"); // 3. 设置POST请求传递参数 //随机数 String nonce = llyUtils.getRund(); //创建时间 格式"yyyy-MM-dd'T'HH:mm:ss'Z'". String created = llyUtils.getCreate(); //密码摘要 String passworddigest = EncryptionToDecryptUtil.getBase64(Hex.encodeHexString(EncryptionToDecryptUtil.String2SHA256(nonce+created+SECRET_KEY+(version+LlyOrder.getMobile()+LlyOrder.getProductCode())).getBytes())); json.put("passworddigest",passworddigest); json.put("nonce",EncryptionToDecryptUtil.getBase64(nonce)); json.put("created",created); json.put("prodid",prodid); //添加请求头 post.addHeader("Authorization", json.toString()); post.addHeader("BipCode", "1111"); post.addHeader("ActivityCode", "1111"); post.addHeader("OrderId", "11111"); post.addHeader("ProductID", prodid); post.addHeader("content-Type", "application/json;charset=utf-8"); List<NameValuePair> params = new ArrayList<NameValuePair>(); //添加请求参数 params.add(new BasicNameValuePair("OrderId", LlyOrder.getOrderNo())); params.add(new BasicNameValuePair("BipActivityCode", BipActivityCode)); try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params); post.setEntity(entity); // 4. 执行请求并处理响应 CloseableHttpResponse responsess = httpClient.execute(post); HttpEntity entitys = responsess.getEntity(); if (entitys != null){ String entitystr = EntityUtils.toString(entitys); jsonObject = JSONObject.fromObject(entitystr); } responsess.close(); }catch (IOException e){ LoggerService.addErrorLog(request,e); e.printStackTrace(); }finally { // 释放资源 try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } }