HttpClient_Get
来源:互联网 发布:肌肉纬度 知乎 编辑:程序博客网 时间:2024/05/29 02:35
首先需要声明 build.gradle 这个文件中,最后面加代码
android { useLibrary 'org.apache.http.legacy'}
public void BtnHttpClient_Get(View view) { new Thread(){ @Override public void run() { super.run(); HttpClientSelect(); } }.start(); } private void HttpClientSelect() { try {// 相当于打开浏览器 HttpClient client = new DefaultHttpClient();// 输入网址,get或者post请求 HttpGet get=new HttpGet("http://apis.juhe.cn/cook/query.php?menu=猪肉炖粉条&key=26ef57b6568ddb188773d1c683879566");// 敲回车 HttpResponse execute = client.execute(get); int code = execute.getStatusLine().getStatusCode(); if(code==200) { InputStream is = execute.getEntity().getContent(); String json = StringTools.Getjson(is); System.out.println("查询的结果:"+json); } } catch (IOException e) { e.printStackTrace(); }
自定义工具类
ublic class StringTools { public static String Getjson(InputStream is) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; while (true) { int m = is.read(b); if (m == -1) { break; } bos.write(b, 0, m); } return bos.toString(); } catch (IOException e) { e.printStackTrace(); } return null; }
阅读全文
0 0