欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android使用url connection示例(get和post数据获取返回数据)

程序员文章站 2022-06-29 09:28:47
一定要加上对sd卡读写文件的权限声明,以及访问网络的权限 复制代码 代码如下:

一定要加上对sd卡读写文件的权限声明,以及访问网络的权限

复制代码 代码如下:

<uses-permission android:name="android.permission.internet" />
<uses-permission android:name="android.permission.write_external_storage" />
<uses-permission android:name="android.permission.read_external_storage"/>

get /post 工具

复制代码 代码如下:

package com.act262.whpj.utils;

import java.io.bufferedreader;
import java.io.file;
import java.io.filewriter;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.io.printstream;
import java.io.printwriter;
import java.net.malformedurlexception;
import java.net.url;
import java.net.urlconnection;
import java.util.date;

import android.os.environment;
import android.util.printstreamprinter;

/**
 * 用于get或者post数据
 */
public class getpostutil {
    public static final string tag = "getpostutil debug";

    /**
     * @param url
     *            传入的url,包括了查询参数
     * @return 返回get后的数据
     */
    public static string sendget(string url) {
        string result = "";
        // string
        url realurl = null;
        urlconnection conn = null;
        bufferedreader bufreader = null;
        string line = "";
        try {
            realurl = new url(url);
        } catch (malformedurlexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
            system.out.println("url 格式错误");
        }

        try {
            conn = realurl.openconnection();
            // 设置连接参数...conn.setrequestproperty("xx", "xx");

            conn.setconnecttimeout(10000); // 10s timeout
            // conn.setrequestproperty("accept", "*/*");
            // conn.setrequestproperty("", "");

            conn.connect(); // 连接就把参数送出去了 get方法

        } catch (ioexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
            system.out.println("连接错误");
        }

        try {
            bufreader = new bufferedreader(new inputstreamreader(
                    conn.getinputstream(), "gb2312"));

            while ((line = bufreader.readline()) != null) {
                result += line + "\n";
            }
        } catch (ioexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
            system.out.println("读取数据错误");
        } finally {
            // 释放资源
            if (bufreader != null) {
                try {
                    bufreader.close();
                } catch (ioexception e) {
                    // todo auto-generated catch block
                    e.printstacktrace();
                }
            }
        }

        return result;
    }

    /**
     * @param url
     * @param param
     *            查询参数 ,形式如 name=xx&age=xx&sex=xx
     * @return
     */
    public static string sendget(string url, string param) {
        return sendget(url + "?" + param);
    }

    /**
     * @param url
     *            指定的url,不包括查询参数
     * @param param
     *            查询参数 形式如 name=xx&age=xx&sex=xx
     * @return 返回post后的数据
     */
    public static string sendpost(string url, string param) {
        string result = "";
        url realurl = null;
        bufferedreader bufreader = null;
        // printwriter printwriter = null;
        printstreamprinter out = null;
        urlconnection connection = null;
        string line = "";
        try {
            realurl = new url(url);
        } catch (malformedurlexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        }
        try {
            connection = realurl.openconnection();
            // 设置为可输入输出 post的模式,而且在输出之前不能获取输入的数据,否则报错
            connection.setdooutput(true);
            connection.setdooutput(true);

            // 已经连接了,所以不能再用connect(),否则报错的

            out = new printstreamprinter(new printstream(
                    connection.getoutputstream()));
            out.println(param);
            //
        } catch (ioexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        }

        try {
            bufreader = new bufferedreader(new inputstreamreader(
                    connection.getinputstream(), "gb2312"));
            while ((line = bufreader.readline()) != null) {
                result += line + "\n";
            }
        } catch (ioexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        } finally {
            // 释放资源
            try {
                if (bufreader != null) {
                    bufreader.close();
                }
                if (out != null) {
                    //
                }
            } catch (ioexception e2) {
                // todo: handle exception
            }

        }
        return result;
    }

    public static void savefile(string content) {

        file file = new file(environment.getexternalstoragedirectory()
                .getabsolutepath(), "file.html");
        if (!file.exists()) {
            try {
                boolean status = file.createnewfile();

                system.out.println("is create new file :" + status);
            } catch (ioexception e) {
                // todo auto-generated catch block
                e.printstacktrace();
            }
        }
        printwriter pw = null;
        try {
            filewriter fw = new filewriter(file);
            // pw = new printwriter(new date() + ".html");
            // pw.println(content);

            fw.write(content);
            fw.flush();

        } catch (ioexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
            if (pw != null) {
                pw.close();
            }
        }
    }

}

测试类

复制代码 代码如下:

package com.act262.whpj.ui;

import android.app.activity;
import android.os.bundle;
import android.os.handler;
import android.os.message;
import android.util.log;
import android.view.menu;
import android.view.view;
import android.view.view.onclicklistener;
import android.widget.button;
import android.widget.textview;

import com.act262.whpj.r;
import com.act262.whpj.utils.getpostutil;

public class startactivity extends activity {

    button get, post;
    textview showtextview;
    handler handler;
    string result = null;

    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_start);
        get = (button) findviewbyid(r.id.get);
        post = (button) findviewbyid(r.id.post);
        showtextview = (textview) findviewbyid(r.id.show);
        handler = new handler() {
            public void handlemessage(message msg) {
                if (msg.what == 0x123) {
                    showtextview.settext(result);
                }
            }
        };
        post.setonclicklistener(new buttonlistener());
        get.setonclicklistener(new buttonlistener());
    }

    @override
    public boolean oncreateoptionsmenu(menu menu) {
        // inflate the menu; this adds items to the action bar if it is present.
        getmenuinflater().inflate(r.menu.start, menu);
        return true;
    }

    class buttonlistener implements onclicklistener {

        @override
        public void onclick(view v) {
            switch (v.getid()) {
            case r.id.get:

                new thread() {

                    public void run() {
                        result = getpostutil
                                .sendget("http://www.baidu.com");
                        handler.sendemptymessage(0x123);// 通知ui线程更新界面
                        // log.d(getpostutil.tag, result);
                        system.out.println(result);
                        getpostutil.savefile(result);
                    }
                }.start();
                showtextview.settext(result);
                break;
            case r.id.post:
                new thread() {
                    public void run() {
                        result = getpostutil
                                .sendpost(
                                        "http://www.baidu.com",
                                        "null");
                        handler.sendemptymessage(0x123);// 通知ui线程更新界面
                        log.d(getpostutil.tag, result);
                    }
                }.start();
                showtextview.settext(result);
                break;
            default:
                break;
            }
        }
    }
}