使用GET和POST从网络上抓取json数据串

xiaoxiao2021-02-28  121

首先要获取网络连接的状态 添加权限 <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> GET方法 //获取连接管理实例 ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); //获取网络状态数组 NetworkInfo info = manager.getActiveNetworkInfo(); if (info.isAvailable()) { try { (//需要传的参数; String value = "menu=" + URLEncoder.encode("牛肉", "utf-8") + "&key=13af589c334ec80c037688e927407966&rn=1"; //访问的网络地址 String path = "http://apis.juhe.cn/cook/query.php?" + value;)//根据自己的需求更改 //获取URL实例 URL url = new URL(path); //获取HttpURLConnection对象 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int code = connection.getResponseCode(); if (code == 200) { System.out.println("访问网络成功"); InputStream is = connection.getInputStream(); String result = ""; String str = ""; BufferedReader reader = new BufferedReader(new InputStreamReader(is)); while ((str = reader.readLine()) != null) { result += str; } System.out.println(result); } } catch (Exception e) { e.printStackTrace(); } } POST方法 try { String path = "http://apis.juhe.cn/cook/query.php"; String value = "menu=" + URLEncoder.encode("韭菜", "utf-8") + "&key=13af589c334ec80c037688e927407966&rn=1"; //post的URL不要加参数值; URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //设置请求方式为post;默认是get; connection.setRequestMethod("POST"); //设置输出数据 connection.setDoOutput(true); //获取一个输出流,用来设置参数 OutputStream stream = connection.getOutputStream(); //将参数放入输出流中; stream.write(value.getBytes()); //获取连接状态码 int code = connection.getResponseCode(); if (code == 200) { //获取请求返回的数据 InputStream inputStream = connection.getInputStream(); //将输入流转换为string BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String result = ""; String str = null; while ((str = reader.readLine()) != null) { result += str; } System.out.println("result"+result); return result; } } catch (Exception e) { e.printStackTrace(); } **这里还可以用另一种post方法来实现 POST答大致方法都差不多最终实现最后的目的就可以**

String path=”http://apis.juhe.cn/cook/query?menu=”+”红烧肉”+”&key=3dbfbb17a76e634a16349d723ea81a31&pn=1&rn=1”;

try { URL url=new URL(path); HttpURLConnection connection= (HttpURLConnection) url.openConnection();

connection.setRequestMethod(“GET”); connection.setConnectTimeout(3000); connection.setReadTimeout(3000); connection.setDoInput(true); int i=connection.getResponseCode(); ByteArrayOutputStream baos=new ByteArrayOutputStream(); if(i==200){ InputStream is=connection.getInputStream(); byte[] buffer=new byte[1024]; int len=-1; while((len=is.read(buffer))!=-1){ baos.write(buffer,0,len); } str=baos.toString(); }

} catch (Exception e) { e.printStackTrace(); }

转载请注明原文地址: https://www.6miu.com/read-18041.html

最新回复(0)