android studio 网络请求

1.基础工具类
public class MyRequest {
    /**
     *服务器基础网址
     */
    public static String severUrl="http://xxx.xx.xx.xx:xx";

    /**
     *Post网址链接
     */
    public String post(String url1, String data) {

        try {
            URL url = new URL(url1);
            //创建链接
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            //两种方法GET POST
            httpURLConnection.setRequestMethod("POST");
            //设置发送数据的格式
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            //设置超时时间
            httpURLConnection.setConnectTimeout(5000);
            httpURLConnection.connect();

            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
            String msg = data;//这里是POST请求需要的参数字符串类型
            dos.write(msg.getBytes(StandardCharsets.UTF_8));
            dos.flush();
            dos.close();//关闭

            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == httpURLConnection.HTTP_OK) {
                //判断请求是否成功
                InputStream inputStream = httpURLConnection.getInputStream();
                ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
                byte[] bytes = new byte[1024];
                int length = 0;
                while ((length = inputStream.read(bytes)) != -1) {
                    arrayOutputStream.write(bytes, 0, length);
                    arrayOutputStream.flush();//强制释放缓冲区
                }
                //读取响应体的内容
                String s = arrayOutputStream.toString();
                return s;//返回请求到的内容,字符串形式
            } else {
                return "链接未成功:-1";//如果请求失败返回-1
            }

        } catch (Exception e) {
            // 出现异常也返回-1
            return e.toString();
        }


    }

    /**
     *get网址链接
     */
    public String get(String url) {

        try {
            //1.HttpURLConnection建立连接,打开链接
            URL requestUrl = new URL(url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) requestUrl.openConnection();

            //两种方法GET POST
            httpURLConnection.setRequestMethod("GET");
            //设置超时时间
            httpURLConnection.setConnectTimeout(3000);
            httpURLConnection.setReadTimeout(3000);

            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == httpURLConnection.HTTP_OK) {

                //2.InputStream获取二进制流
                InputStream inputStream = httpURLConnection.getInputStream();
                ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
                byte[] bytes = new byte[1024];
                int length = 0;
                while ((length = inputStream.read(bytes)) != -1) {
                    arrayOutputStream.write(bytes, 0, length);
                    arrayOutputStream.flush();//强制释放缓冲区
                }
                String s = arrayOutputStream.toString();
                return s;
            } else {
                return "-1";
            }
        } catch (Exception e) {
            return "-1";
        }

    }

    /**
     *HttpClientPost网址链接
     */
    public String httpClientPost(String url, String jsonData) {

        String result = "";
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            //创建请求头对象
            BasicHttpClientResponseHandler handler = new BasicHttpClientResponseHandler();
            //设置请求格式,utf-8解决中文乱码
            StringEntity entity = new StringEntity(jsonData, ContentType.parse("application/json;charset=UTF-8"));
            httpPost.setEntity(entity);
            //执行POST请求
            result = httpClient.execute(httpPost, handler);
            return result;
        } catch (Exception e) {
            return  e.toString();
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                Log.d("网络链接", "httpClientPost: 没有成功关闭!");
            }
        }
    }

    /**
     *获取注册网址
     */
    public  String getRegisterUrl(){
        return  severUrl+"/Account/Register";
    }
    /**
     *获取激活网址
     */
    public  String getActiveUrl(){
        return  severUrl+"/Ticket/Active";
    }
    /**
     *获取登录网址
     */
    public  String getLoginUrl(){
        return  severUrl+"/Account/Login";
    }


}

2.应用

btn_checkData.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        //异步请求网址
        new Thread(new Runnable() {
            @Override
            public void run() {

                MyRequest request = new MyRequest();
                loginUrl = request.getLoginUrl();
                String res = request.httpClientPost(loginUrl, strJson);
                Log.d("扳机请求:", res);
                //异步线程更新UI视图
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        Log.d("扳机请求:", res);

                    }
                });

            }
        }).start();

    }

});

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值