栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

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

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

复制代码 代码如下:



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;


public class GetPostUtil {
    public static final String TAG = "GetPostUtil Debug";

   
    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", "*
    public static String sendGet(String url, String param) {
        return sendGet(url + "?" + param);
    }

   
    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;
            }
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/164770.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号