美文网首页
Android中HttpURLConnection

Android中HttpURLConnection

作者: MissmoBaby | 来源:发表于2017-07-18 14:33 被阅读0次

大部分安卓项目开发中,网络请求都是用封装好的网络框架,如:okhttp、nohttp、volley等。导致基础的HttpURLConnection和HttpClient基本不会自己写了,基于安卓6.0SDK删除了HttpClient了,因此只回顾一下HttpURLConnection的用法。

Get方式:

// Get方式请求  
public static void requestByGet() throws Exception {  
    String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";  
    // 新建一个URL对象  
    URL url = new URL(path);  
    // 打开一个HttpURLConnection连接  
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
    // 设置连接超时时间  
    urlConn.setConnectTimeout(5 * 1000);  
    // 开始连接  
    urlConn.connect();  
    // 判断请求是否成功  
    if (urlConn.getResponseCode() == HTTP_200) {  
        // 获取返回的数据  
        byte[] data = readStream(urlConn.getInputStream());  
        Log.i(TAG_GET, "Get方式请求成功,返回数据如下:");  
        Log.i(TAG_GET, new String(data, "UTF-8"));  
    } else {  
        Log.i(TAG_GET, "Get方式请求失败");  
    }  
    // 关闭连接  
    urlConn.disconnect();  
}  

Post方式:

// Post方式请求  
public static void requestByPost() throws Throwable {  
    String path = "https://reg.163.com/logins.jsp";  
    // 请求的参数转换为byte数组  
    String params = "id=" + URLEncoder.encode("helloworld", "UTF-8")  
            + "&pwd=" + URLEncoder.encode("android", "UTF-8");  
    byte[] postData = params.getBytes();  
    // 新建一个URL对象  
    URL url = new URL(path);  
    // 打开一个HttpURLConnection连接  
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
    // 设置连接超时时间  
    urlConn.setConnectTimeout(5 * 1000);  
    // Post请求必须设置允许输出  
    urlConn.setDoOutput(true);  
    // Post请求不能使用缓存  
    urlConn.setUseCaches(false);  
    // 设置为Post请求  
    urlConn.setRequestMethod("POST");  
    urlConn.setInstanceFollowRedirects(true);  
    // 配置请求Content-Type  
    urlConn.setRequestProperty("Content-Type",  
            "application/x-www-form-urlencode");  
    // 开始连接  
    urlConn.connect();  
    // 发送请求参数  
    DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());  
    dos.write(postData);  
    dos.flush();  
    dos.close();  
    // 判断请求是否成功  
    if (urlConn.getResponseCode() == HTTP_200) {  
        // 获取返回的数据  
        byte[] data = readStream(urlConn.getInputStream());  
        Log.i(TAG_POST, "Post请求方式成功,返回数据如下:");  
        Log.i(TAG_POST, new String(data, "UTF-8"));  
    } else {  
        Log.i(TAG_POST, "Post方式请求失败");  
    }  
}  

相关文章

网友评论

      本文标题:Android中HttpURLConnection

      本文链接:https://www.haomeiwen.com/subject/rschkxtx.html