HttpUrlconnction_post

来源:互联网 发布:温度控制pid算法c程序 编辑:程序博客网 时间:2024/06/04 23:24
//    自定义按钮的点击事件方法    public void BtnConnection(View view)    {        new Thread(){            @Override            public void run() {                super.run();//                自定义方法使用post请求                HttpUrlConectionPost();            }        }.start();    }    private void HttpUrlConectionPost() {        try {            URL url=new URL("http://apis.juhe.cn/cook/query.php");            HttpURLConnection connection= (HttpURLConnection) url.openConnection();            connection.setRequestMethod("POST");            connection.setConnectTimeout(5000);            connection.setReadTimeout(5000);            OutputStream os = connection.getOutputStream();//            如果出现状态码202的话是因为这里的Menu值无法识别,使用UrlENcoder.encode()设置编码格式            os.write(("key=6666666666666666&menu="+ URLEncoder.encode("西红柿炒鸡蛋","utf-8")).getBytes());            os.flush();            os.close();            int code = connection.getResponseCode();            if(code==200)            {                InputStream is = connection.getInputStream();                String json = StringTools.GetString(is);                Gson gson = new Gson();                bean bean = gson.fromJson(json, bean.class);            }        } catch (Exception e) {            e.printStackTrace();

}

自定义工具类

public class StringTools {    public static String GetString(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;    }}

原创粉丝点击