HttpClient

来源:互联网 发布:广东多益网络 编辑:程序博客网 时间:2024/05/09 03:05

HttpClient

httpClient api的使用,发送get和post请求。
HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性。

get获取数据

String connectPath = "";HttpClient client = new DefaultHttpClient();HttpGet get = new HttpGet(connectPath);HttpResponse response;try {    response = client.execute(get);    StatusLine sl = response.getStatusLine();    if (sl.getStatusCode() == 200) {        HttpEntity entity = response.getEntity();        InputStream is = entity.getContent();        // 读取流中的数据        byte[] b = new byte[1024];        int len;        ByteArrayOutputStream bos = new ByteArrayOutputStream();        while ((len = is.read(b)) != -1) {            bos.write(b, 0, len);        }        String strJson = new String(bos.toByteArray());    }} catch (Exception e) {    e.printStackTrace();}

post发送数据

String packagePath = "";HttpClient client = new DefaultHttpClient();HttpPost post = new HttpPost(packagePath);List<NameValuePair> parameters = new ArrayList<NameValuePair>();NameValuePair nvp = new BasicNameValuePair("package_list",        "我是package_list的值");NameValuePair nvp2 = new BasicNameValuePair("label_list",        "我是label_list的值");parameters.add(nvp);parameters.add(nvp2);try {    HttpEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");    post.setEntity(entity);    HttpResponse response = client.execute(post);    if (response.getStatusLine().getStatusCode() == 200) {        Log.d("ziru", "post发送成功");    }} catch (Exception e) {    e.printStackTrace();}
0 0
原创粉丝点击