HttpURLConnection、HttpClient请求网络数据、Xutils的HttpUtils 请求数据

一、添加连网权限

 <uses-permission android:name="android.permission.INTERNET"/>

二、Java代码
HttpURLConnection的get的请求

public static InputStream doget(String path) {
        // 有参数的话拼接字符串
        // 例:String
        // path="http://169.254.135.196:8080/logservlet?username="+username+"&&password="+password;
        URL url;
        try {
            // 创建url对象
            url = new URL(path);
            // 连接
            HttpURLConnection httpURLConnection = (HttpURLConnection) url
                    .openConnection();
            // 设置请求方式
            httpURLConnection.setRequestMethod("GET");
            // 设置连接超时
            httpURLConnection.setConnectTimeout(5000);
            // 设置读取超时
            httpURLConnection.setReadTimeout(5000);
            // 得到响应吗
            int responseCode = httpURLConnection.getResponseCode();

            if (responseCode == 200) {

                // 返回输入流
                InputStream inputStream = httpURLConnection.getInputStream();
                return inputStream;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

HttpURLConnection的post的请求

public static InputStream dopost(String path) {
        URL url;
        try {
            // 有参数(更改编码格式)
            // String data
            // ="username="+URLEncoder.encode("name","utf-8")+"&&password="+password;
            // 创建url对象
            url = new URL(path);
            // 连接
            HttpURLConnection httpURLConnection = (HttpURLConnection) url
                    .openConnection();
            // 设置请求方式
            httpURLConnection.setRequestMethod("POST");
            // 设置连接超时
            httpURLConnection.setConnectTimeout(5000);
            // 设置读取超时
            httpURLConnection.setReadTimeout(5000);

            /*
             * 如果有参数,把注释代码解开
             */
            // 如果是true,表示允许客户端向服务器发送数据
            // httpURLConnection.setDoOutput(true);
            // 向服务器发送数据
            // httpURLConnection.getOutputStream().write(data.getBytes());

            // 得到响应吗
            int responseCode = httpURLConnection.getResponseCode();

            if (responseCode == 200) {
                // 返回输入流
                InputStream inputStream = httpURLConnection.getInputStream();
                return inputStream;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

HttpClient的get请求

public static InputStream dogetprase(String path) {
        // 创建httpClient对象
        HttpClient httpClient = new DefaultHttpClient();
        // 获取请求方式
        HttpGet get = new HttpGet(path);
        try {
            // 执行请求
            HttpResponse response = httpClient.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
             //返回字符串
               // String string = EntityUtils.toString(response.getEntity());
               //返回流
                InputStream inputStream = response.getEntity().getContent();
                return inputStream;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

HttpClient的post请求

public static InputStream dopostprase(String path) {
        // 创建httpClient对象
        HttpClient httpClient = new DefaultHttpClient();
        // 获取请求方式
        HttpPost post = new HttpPost(path);
        try {
            //需要参数就把注释代码解开
            // 需要携带的参数
            // List<NameValuePair> paNameValuePairs = new
            // ArrayList<NameValuePair>();

            // paNameValuePairs.add(new BasicNameValuePair("username", "张三"));
            // paNameValuePairs.add(new BasicNameValuePair("password", "123"));

            // 创建UrlEncodedFormEntity的实例
            // HttpEntity entity = new UrlEncodedFormEntity(paNameValuePairs);
            // post带参数
            // post.setEntity(entity);
            // 执行请求
            HttpResponse response = httpClient.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                InputStream inputStream = response.getEntity().getContent();
                return inputStream;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

Xutils的HttpUtils 请求数据

public void qingqiu() {
        String path = "http://www.oschina.net/action/api/news_list?catalog=1&&pageindex="
                + i + "&&pageSize=20";
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpMethod.GET, path, new RequestCallBack<String>() {

            @Override//请求失败的方法
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub

            }

            @Override//请求成功的方法
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result;
                inputStream = new ByteArrayInputStream(result.getBytes());

                Gsonutil gsonutil = new Gsonutil();

                List<User_ziyun> list = gsonutil.parser(getActivity(),
                        inputStream);

                Message msg = Message.obtain();
                msg.what = 1;
                msg.obj = list;
                handler.sendMessage(msg);
            }
        });
    };

util将InputStream转为String

public class UtilInputStr {
        public static String readInputStream(InputStream input) {  
           ByteArrayOutputStream output = new ByteArrayOutputStream();  
           try {  
               byte[] buffer = new byte[1024];  
               int len = 0;  
               while((len = input.read(buffer)) != -1) {  
                  output.write(buffer, 0, len);  
               }  
           } catch (IOException e) {  
               // TODO Auto-generated catch block  
               e.printStackTrace();  
           }  
           return output.toString();  
        }  
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值