Android 万能Get请求Json方法
发布日期:2021-09-28 18:45:53 浏览次数:5 分类:技术文章

本文共 2485 字,大约阅读时间需要 8 分钟。

package com.example.h3c.net;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.ConnectException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import android.util.Log;import com.example.pickride.util.ConstantsTable;public class HttpConnection {    private final int TIMEOUT = 3000;// 设定超时时间    /**     * 请求服务器响应     *      * @param requestType     *            请求类型 requestContent [类型,参数,类型,参数]     */    public String requestService(String requestType, String... requestContent) {        String resultData = "";        InputStreamReader in = null;        HttpURLConnection urlConn = null;        BufferedReader buffer = null;        try {            StringBuffer sBuffer = new StringBuffer();            for (int n = 0; n < requestContent.length; n++) {                if ((n + 1) % 2 == 0) {                    sBuffer.append("=" + requestContent[n] + "&");                } else {                    sBuffer.append(requestContent[n]);                }            }            URL url = new URL(ConstantsTable.URI + requestType + "?" + sBuffer);            if (url != null) {                urlConn = (HttpURLConnection) url.openConnection();                urlConn.setConnectTimeout(TIMEOUT);// 设置超时时间                try {                    in = new InputStreamReader(urlConn.getInputStream());                } catch (ConnectException e) {                    Log.e(ConstantsTable.LOG_TAG, "服务器宕机了...");                    return resultData;                }                buffer = new BufferedReader(in);                String inputLine = null;                while ((inputLine = buffer.readLine()) != null) {                    resultData += inputLine + "\n";                }                urlConn.disconnect();                if (ConstantsTable.DEBUG_FLAG) {                    Log.d(ConstantsTable.LOG_TAG, resultData);                }            }        } catch (MalformedURLException e) {            Log.e(ConstantsTable.LOG_TAG, "域名无法解析");            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                if (in != null) {                    in.close();                }                if (buffer != null) {                    buffer.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }        return resultData;    }}

转载地址:https://blog.csdn.net/h3c4lenovo/article/details/8128457 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Android Design 从头开始
下一篇:Android Json数据解析

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月17日 19时33分21秒