HttpClient_Post

来源:互联网 发布:php 过滤非utf8字符 编辑:程序博客网 时间:2024/05/16 14:31
记得在  build.gradle 加一行声明,否则用不了HttpClient,安卓6.0以后不支持使用,建议使用HttpUrlConnection
android {    useLibrary 'org.apache.http.legacy'}
public void btnHttpClient_Post(View view)    {        new Thread(){            @Override            public void run() {                super.run();                selectHttpClient();            }        }.start();    }    private void selectHttpClient() {        try {//            打开浏览器            HttpClient client = new DefaultHttpClient();//            填入网址,设置访问方式            HttpPost post=new HttpPost("http://apis.juhe.cn/catering/query");//post请求添加参数            List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();            list.add(new BasicNameValuePair("lng","121.538123"));            list.add(new BasicNameValuePair("key","8594ec18ce64a17b5f8f20e1f5c9e4c0"));            list.add(new BasicNameValuePair("lat","31.677132"));//设置请求正文            post.setEntity(new UrlEncodedFormEntity(list));//敲回车            HttpResponse execute = client.execute(post);//得到状态码            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();        }
原创粉丝点击