java 调用接口 httpClent get post请求 token认证


/**
get请求 传递token
*/
	static String doGet(String url,Map params,String token){
		BufferedReader in = null;
		CloseableHttpResponse response=null;
		//1.创建HttpClient对象
		CloseableHttpClient httpClient= HttpClients.createDefault();
	try {
		httpClient= HttpClients.createDefault();
      URIBuilder uriBuilder=new URIBuilder(url);
      //设置参数
      if (params!=null&&params.size()>0) {
    	  for (Object param : params.keySet()) {
    		  uriBuilder.setParameter(param+"",params.get(param)+"");
		}
	}
        //2.创建HttpGet对象,设置URL地址
      HttpGet httpGet=new HttpGet(uriBuilder.build());
      if (!StringUtils.isBlank(token)) { //设置请求token
    	  httpGet.setHeader("Authorization", "Bearer " + token);
		}
      System.out.println("发送请求的信息:"+httpGet);
      //使用httpClient发起响应获取repsonse
          response=httpClient.execute(httpGet);
          //4.解析响应,获取数据   判断状态码是否是200
          if(response.getStatusLine().getStatusCode()==200){
				in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
				StringBuffer sb = new StringBuffer("");
				String line = "";
				String NL = System.getProperty("line.separator");
				while ((line = in.readLine()) != null) {
					sb.append(line + NL);
				}

				in.close();
				return sb.toString();
          }
          System.out.println("请求状态码----"+response.getStatusLine().getStatusCode());
      } catch (Exception e) {
          e.printStackTrace();
      }
		return null;
		
	}
``/**
	 * post请求(用于key-value格式的参数)
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doPost(String url, Map params) {
		BufferedReader in = null;
		try {
			// 定义HttpClient
			HttpClient client =HttpClients.createDefault();
			// 实例化HTTP方法
			HttpPost request = new HttpPost();
			request.setURI(new URI(url));
//			if (StringUtils.isBlank(token)) {
//				request.setHeader("Authorization", "Bearer " + token);
//			}

			// 设置参数
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String value = String.valueOf(params.get(name));
				nvps.add(new BasicNameValuePair(name, value));
			}
			request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

			HttpResponse response = client.execute(request);
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) { // 请求成功
				in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
				StringBuffer sb = new StringBuffer("");
				String line = "";
				String NL = System.getProperty("line.separator");
				while ((line = in.readLine()) != null) {
					sb.append(line + NL);
				}

				in.close();

				return sb.toString();
			} else { //
				System.out.println("状态码:" + code);
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();

			return null;
		}
	}

	/**
	 * post请求(用于请求json格式的参数)
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doPost(String url, String params) throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);// 创建httpPost
		httpPost.setHeader("Accept", "text/plain");
		httpPost.setHeader("Content-Type", "application/json-patch+json");
		String charSet = "UTF-8";
		StringEntity entity = new StringEntity(params, charSet);
		httpPost.setEntity(entity);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httpPost);
			StatusLine status = response.getStatusLine();
			int state = status.getStatusCode();
			if (state == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				String jsonString = EntityUtils.toString(responseEntity);
				return jsonString;
			} else {
			}
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	

你可能感兴趣的:(Java,java,servlet,开发语言)