Android HttpUrlConnection如何使用Https连接

一个小的demo

    public String login(String uid, String password){
        HttpsURLConnection connection=null;
        try {
        TrustManagerFactory tmf =  TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore trusted = KeyStore.getInstance("PKCS12", "BC");
            trusted.load(null, null);
            InputStream in = getAssets().open("server.crt");
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            Certificate certificate = certificateFactory.generateCertificate(in);
            trusted.setCertificateEntry("trust", certificate);
            in.close();

            tmf.init(trusted);

            TrustManager[] tms = tmf.getTrustManagers();

            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null,tms,new SecureRandom());
            URL url = new URL("https://127.0.0.1:8080/login");
            connection= (HttpsURLConnection)url.openConnection();
            connection.setSSLSocketFactory(sc.getSocketFactory());
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(3000);//连接的超时时间
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("charset", "utf-8");
            connection.connect();
            OutputStreamWriter osw=new OutputStreamWriter(connection.getOutputStream());
            osw.write("uid="+uid+"&pass_word="+password);
            osw.flush();
            osw.close();
            BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder sb=new StringBuilder();
            String aLine=null;
            while ((aLine=reader.readLine())!=null){
                sb.append(aLine).append("\n");
            }
            reader.close();
            return sb.toString();
        }catch (Exception e){
            e.printStackTrace();
            return e.getMessage();
        }finally {
            if(connection!=null){
                connection.disconnect();
            }
        }
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为了使用HttpURLConnection来发送和接收HTTP请求和响应,您需要按照以下步骤操作: 1. 创建HttpURLConnection对象,并将其连接到URL对象。例如: URL url = new URL("http://www.example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 2. 设置请求方法和连接属性,如连接超时和读取超时。例如: conn.setRequestMethod("POST"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); 3. 添加请求头(可选)。例如: conn.setRequestProperty("User-Agent", "Android"); conn.setRequestProperty("Content-Type", "application/json"); 4. 如果POST请求,添加请求体。例如: String requestBody = "{\"username\":\"user123\",\"password\":\"pass123\"}"; OutputStream outputStream = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); writer.write(requestBody); writer.flush(); writer.close(); outputStream.close(); 5. 发送请求,获取响应码和响应数据。例如: int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder responseData = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { responseData.append(line); } reader.close(); inputStream.close(); String responseString = responseData.toString(); } 以上是使用HttpURLConnection发送和接收HTTP请求和响应的基本步骤。具体实现需根据具体的业务需求和网络情况进行调整和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值