平时在大家学习工作中,会遇到给你一个接口让你去获取对应数据,里面也包含了post请求和get请求。下面给大家提供对应的工具类。
一、Java代码实现发送get请求
public static String getpage(String tempurl,String bm,String token ) { String result=""; try { URL url = new URL(tempurl); InputStream is = null; URLConnection con=url.openConnection(); con.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); con.setConnectTimeout(120000); con.setReadTimeout(120000); con.addRequestProperty("x-access-token",token); con.connect(); try { is = con.getInputStream(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(is,bm)); String s=""; String linesep = System.getProperty("line.separator"); while((s = reader.readLine())!=null){ result += s+linesep ; } reader.close(); } catch (Exception e) { e.printStackTrace(); }finally { if (reader != null) { try { reader.close(); } catch (Exception e1) { } } } is.close(); }catch (FileNotFoundException e2) { ; } } catch (Exception e1) { e1.printStackTrace(); } return result; }
二、Java代码实现发送post请求
private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class); public static String sendPost(JSONObject json, String URL,String token) { CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(URL); post.setHeader("Content-Type", "application/json"); post.setHeader("Authorization", "Basic YWRtaW46"); post.setHeader("x-access-token",token); String result; try { StringEntity s = new StringEntity(json.toString(), "utf-8"); s.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(s); // 发送请求 HttpResponse httpResponse = client.execute(post); // 获取响应输入流 InputStream inStream = httpResponse.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader( inStream, "utf-8")); StringBuilder strber = new StringBuilder(); String line; while ((line = reader.readLine()) != null) strber.append(line + "\n"); inStream.close(); result = strber.toString(); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { System.out.println("请求服务器成功,做相应处理"); } else { System.out.println("请求服务端失败"); } } catch (Exception e) { logger.error("请求异常:"+e.getMessage()); throw new RuntimeException(e); } return result; }
在使用过程中注意:各类参数设置正确