Httpclient_post解析

来源:互联网 发布:绿盟笔试题python 编辑:程序博客网 时间:2024/05/21 11:22

protected void getData() {

    // 得到HttpClient对象    HttpClient client = new DefaultHttpClient();    // 通过post方式请求    HttpPost httpPost = new HttpPost(path);    // 得到集合,添加需要携带的请求参数    List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();    String name = null;    try {        //经过编码的汉字  ///%E7%99%BD%E7%BE%8A%E5%BA%A7                     ///%E7%99%BD%E7%BE%8A%E5%BA%A7        name = URLEncoder.encode("狮子座", "utf-8");    } catch (UnsupportedEncodingException e1) {        // TODO Auto-generated catch block        e1.printStackTrace();    }    parameters.add(new BasicNameValuePair("consName", name));    parameters.add(new BasicNameValuePair("type", "today"));    parameters.add(new BasicNameValuePair("key",            "3ac9f31ff66b9746539472887b3799c3"));    try {        // 得到实体对象        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(                parameters);        // 设置请求实体        httpPost.setEntity(formEntity);        // 连接,得到响应回来的数据        HttpResponse httpResponse = client.execute(httpPost);        // 得到状态行,在得到的状态码        if (httpResponse.getStatusLine().getStatusCode() == 200) {            // 得到实体            HttpEntity entity = httpResponse.getEntity();            // 得到字符串数据            String data = EntityUtils.toString(entity);            System.out.println(data);            // 解析json            Gson gson = new Gson();            Bean bean = gson.fromJson(data, Bean.class);            // 把数据发给主线程            Message msg = Message.obtain();            msg.obj = bean;            handler.sendMessage(msg);        } else {            Toast.makeText(MainActivity.this, " 连接错误  ", 1).show();        }    } catch (ClientProtocolException e) {        // TODO Auto-generated catch block        e.printStackTrace();    } catch (IOException e) {        // TODO Auto-generated catch block        e.printStackTrace();    }}
0 0
原创粉丝点击