微信网站怎么做,给人做网站,扬中网络推广,营销公司网站模板加哥最近做第三方接口开发#xff0c;对方提供的是get方式的http请求#xff0c;下面加哥给大家进行了总结如何用java代码去发送http请求并获取结果。
下面是发送get请求的工具类
1.不要求携带token的方式
public static String getUrl(String tempurl,String bm) {String…加哥最近做第三方接口开发对方提供的是get方式的http请求下面加哥给大家进行了总结如何用java代码去发送http请求并获取结果。
下面是发送get请求的工具类
1.不要求携带token的方式
public static String getUrl(String tempurl,String bm) {String result;try {URL url new URL(tempurl);InputStream is null;URLConnection conurl.openConnection();con.addRequestProperty(User-Agent, Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt));con.setConnectTimeout(120000);con.setReadTimeout(120000);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 slinesep ;}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;}
下面是使用封装的好的请求工具类发送请求
public static void main(String[] args) {String str http://110.43.47.12:8089/system/sim?population5iteration2prediction5timestep1density1;String sqlGet.getUrl(str,utf-8);System.out.println(sql);}
注意请求发送后返回来的是JSON字符串大家对其进行解析获取自己需要的数据即可。此外还需注意第二个参数是编码格式。
2.要求携带token的方式
public static String getpage(String tempurl,String bm,String token ) { String result; try { URL url new URL(tempurl); InputStream is null; URLConnection conurl.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 slinesep ; } 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; }