[Android开发] Android客户端使用HTTP通信

Android作为客户端(client)对服务器(server)进行request操作,并从服务器中得到response。
这里主要使用HTTP来进行数据传输,request有GET和POST两种方式。

注意

  • 以下代码可以检测网络是否连接,但不包括hotspot的连接。
/**
 * Check network connection.
 *
 * @return true if connected.
 */
private boolean isNetworkConnected() {
    ConnectivityManager mConnectivityManager = (ConnectivityManager) mContext
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
    return mNetworkInfo != null && mNetworkInfo.isConnected();
}

代码

RequestTask类封装了AsyncTask,实现了异步通信等细节。

  • RequestTask.java
package com.example.android.networkconnect;

import android.os.AsyncTask;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Implementation of AsyncTask, to fetch the data in the background away from the UI thread.
 */
public class RequestTask extends AsyncTask<String, Void, String> {

    public static final String TAG = "RequestTask";
    private static final int CONNECT_TIMEOUT = 15000 /* milliseconds */;
    private static final int BUFFER_SIZE = 32;
    private boolean isPost = false;

    /**
     * Set POST method.
     *
     * @param isPost true if post.
     */
    public void setPost(boolean isPost) {
        this.isPost = isPost;
    }

    @Override
    protected String doInBackground(String... strings) {
        try {
            String result = "";

            HttpURLConnection conn;
            if (isPost) {
                conn = doPost(strings[0], strings[1]);
            } else {
                conn = doGet(strings[0]);
            }
            // Success HTTP Status Code
            if (conn.getResponseCode() / 100 != 2)
                return result;
            result = getStringFromStream(conn.getInputStream());
            return result;
        } catch (IOException e) {
            return e.getLocalizedMessage();
        }
    }

    /**
     * Given a string representation of a URL, sets up a connection for GET request.
     *
     * @param urlString A string representation of a URL.
     * @return A HttpURLConnection.
     * @throws java.io.IOException
     */
    private HttpURLConnection doGet(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.connect();
        return conn;
    }

    /**
     * Given a string representation of a URL, sets up a connection for POST request.
     *
     * @param urlString A string representation of a URL.
     * @param postData  Post data.
     * @return A HttpURLConnection.
     * @throws java.io.IOException
     */
    private HttpURLConnection doPost(String urlString, String postData) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(CONNECT_TIMEOUT);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", Integer.toString(postData.length()));
        DataOutputStream dataOutputStream = null;
        try {
            dataOutputStream = new DataOutputStream(conn.getOutputStream());
            dataOutputStream.writeBytes(postData);
        } finally {
            if (dataOutputStream != null)
                dataOutputStream.close();
        }
        return conn;
    }

    /**
     * Reads an InputStream and converts it to a String.
     *
     * @param inputStream InputStream.
     * @return String from inputStream.
     * @throws java.io.IOException
     */
    private String getStringFromStream(InputStream inputStream) throws IOException {
        InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
        StringBuilder sb = new StringBuilder(BUFFER_SIZE);
        char[] buffer = new char[BUFFER_SIZE];
        int length;
        while ((length = isr.read(buffer, 0, BUFFER_SIZE)) != -1) {
            sb.append(buffer, 0, length);
            if (isCancelled())
                return null;
        }
        inputStream.close();
        isr.close();
        return sb.toString();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值