首页 > 代码库 > Android利用Get、Post 获取网络数据

Android利用Get、Post 获取网络数据

首先是Get:

布局很简单,就一个按钮,主要看一下MainActivity吧:

package com.francis.httpget;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class MyActivity extends Activity {

    BufferedReader bufferedReader;
    InputStreamReader inputStreamReader;
    InputStream inputStream;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AsyncTask<String,Void,Void>() {
                    @Override
                    protected Void doInBackground(String... params) {
                        try {
                            URL url = new URL(params[0]);
                            URLConnection connection = url.openConnection();

                            inputStream = connection.getInputStream();
                            inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
                            bufferedReader = new BufferedReader(inputStreamReader);

                            String line;
                            while (true) {
                                if ((line = bufferedReader.readLine()) != null) {
                                    System.out.println(line);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                bufferedReader.close();
                                inputStreamReader.close();
                                inputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                        return null;
                    }
                }.execute("http://fanyi.youdao.com/openapi.do?keyfrom=HttpGetFrancis&key=893755706&type=data&doctype=xml&version=1.1&q=这里是有道翻译API");
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.my, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

url为有道翻译提供的API,非常方便。控制台输出如图:



接着是Post:

很简单,这里只给出提交post请求的Button的点击事件:

和Get相比有2点需要注意:

1.url与参数是分开的;

2.connection.setDoInput(true);
   connection.setDoOutput(true);
   connection.setRequestMethod("POST");

// Post
        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AsyncTask<String,Void,Void>() {
                    @Override
                    protected Void doInBackground(String... params) {
                        try {
                            URL url = new URL(params[0]);
                            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                            connection.setDoInput(true);
                            connection.setDoOutput(true);
                            connection.setRequestMethod("POST");

                            outputStream = connection.getOutputStream();
                            outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
                            bufferedWriter = new BufferedWriter(outputStreamWriter);
                            bufferedWriter.write("keyfrom=HttpGetFrancis&key=893755706&type=data&doctype=xml&version=1.1&q=这里是有道翻译API");
                            bufferedWriter.flush();

                            inputStream = connection.getInputStream();
                            inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
                            bufferedReader = new BufferedReader(inputStreamReader);

                            String line;
                            while (true) {
                                if ((line = bufferedReader.readLine()) != null) {
                                    System.out.println(line);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                bufferedReader.close();
                                inputStreamReader.close();
                                inputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                        return null;
                    }
                }.execute("http://fanyi.youdao.com/openapi.do");
            }
        });


Android利用Get、Post 获取网络数据