Android中网络获取数据的方法

建一个布局:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView   xmlns:android="http://schemas.android.com/apk/res/android"

              android:layout_width="match_parent"
              android:layout_height="match_parent">
<LinearLayout
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <EditText android:layout_width="match_parent"
              android:layout_height="wrap_content"
            android:id="@+id/httpEditeText"
            android:text="123"/>
<Button android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/httpButton"
        android:text="点击获取服务数据"/>
    <Button android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:onClick="packageButton"
            android:text="用类封装获取网络数据"/>
    <TextView android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:textSize="20dp"
              android:id="@+id/httpTextView"/>
</LinearLayout>
</ScrollView>

关联布局的Activity:

package com.scxh.htmlandhttp;

import android.app.Activity;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.scxh.R;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Administrator on 15-1-7.
 */
public class HttpActivity extends Activity {
    private String httpPath="http://192.168.1.154:8080/web/demoservlet";
    private String baidu="http://www.baidu.com/";
    private Button httpBtn,packageBtn;
    private TextView httpTv;
    private EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http);
        editText=(EditText)findViewById(R.id.httpEditeText);
        httpBtn=(Button)findViewById(R.id.httpButton);

        httpTv=(TextView)findViewById(R.id.httpTextView);

        httpBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
             new AsyncTask<String,Void,String>(){
                 @Override
                 protected String doInBackground(String... strings) {
                     String httpUrl=strings[0];
                     /*调用获取网络数据的方法*/
                     String content= null;
                     try {
                         content = getApacheData(httpUrl);
                     } catch (UnsupportedEncodingException e) {
                         e.printStackTrace();
                     }
                     return content;
                 }

                 @Override
                 protected void onPostExecute(String s) {
                     httpTv.setText(s);
                 }
             }.execute(editText.getText().toString());
            }
        });

    }
    /*利用封装好类,来获取网络数据*/
    public void packageButton(View view){
        HttpIntentPackage.HttpConnectInterface httpConnectInterface=new HttpIntentPackage.HttpConnectInterface() {
            @Override
            public void execute(String result) {
                httpTv.setText(result);
            }
        };
        HashMap<String,String> parameters=new HashMap<String, String>();
        parameters.put("userName","陈刚");
        parameters.put("passWord","表演节目");
    /*利用Json传输数据*/
        JSONObject jsonObject=new JSONObject(parameters);
        String json=jsonObject.toString();
        HashMap<String,String> param=new HashMap<String, String>();
        param.put("jsonStr",json);
    /*利用Json传输数据*/

        HttpIntentPackage httpIntentPackage=new HttpIntentPackage();
        httpIntentPackage.asyncConnect(httpPath,
                HttpIntentPackage.HttpMethod.POST,param);
        httpIntentPackage.setmHttpConnectInterface(httpConnectInterface);
    }
    /*实现客服端与服务端的链接*/
    /*用JAVA从网络获取数据*/
    private String getIntentData(String url){
        InputStream is=null;
        BufferedReader br=null;
        StringBuffer sb = null;
        HttpURLConnection connection=null;
        try {
            //封装访问服务器地址
            URL url1=new URL(url);
            //打开对服务器的链接
            connection=(HttpURLConnection)url1.openConnection();

            connection.setRequestMethod("GET");//利用GET方法取数据
            //链接服务器
            connection.connect();
            //得到输入流
            is=connection.getInputStream();
            //创建包装流
            br=new BufferedReader(new InputStreamReader(is));
            //定义String类型用于存储单行数据
            String line=null;
            //创建StringBuffer对象用于存储所有数据
            sb=new StringBuffer();
            while ((line=br.readLine())!=null){
                sb.append(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            connection.disconnect();
            if (br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
    /*利用apache获取网络数据*/
    private String getApacheData(String url) throws UnsupportedEncodingException {
        InputStream is=null;
        BufferedReader br=null;
        StringBuffer sb = new StringBuffer();
        HttpClient httpClient=new DefaultHttpClient();
        HttpPost httpPost=new HttpPost(url);
        /*利用post传参152-162*/
 /*       BasicNameValuePair userNamePair=new BasicNameValuePair("userName","四川新华");
        Log.e("userNamePair",userNamePair+"");

        BasicNameValuePair passWordPair=new BasicNameValuePair("passWord","12315");
        Log.e("passWordPair",passWordPair+"");
        ArrayList<BasicNameValuePair> arrayList=new ArrayList<BasicNameValuePair>();
        arrayList.add(userNamePair);
        arrayList.add(passWordPair);

        UrlEncodedFormEntity entity=new UrlEncodedFormEntity(arrayList,HTTP.UTF_8);
        httpPost.setEntity(entity);*/
        try {
            HttpResponse httpResponse=httpClient.execute(httpPost);
            HttpEntity httpEntity=httpResponse.getEntity();
            is=httpEntity.getContent();

            int statusCode=httpResponse.getStatusLine().getStatusCode();
            if (statusCode==200){
                //创建包装流
                br=new BufferedReader(new InputStreamReader(is));
                //定义String类型用于存储单行数据
                String line=null;
                //创建StringBuffer对象用于存储所有数据
                sb=new StringBuffer();
                while ((line=br.readLine())!=null){
                    sb.append(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sb.toString();
    }
    /*利用安卓方法获取数据*/
    private String getAndroidData(String url){
        InputStream is=null;
        BufferedReader br=null;
        StringBuffer sb=new StringBuffer();
        AndroidHttpClient androidHttpClient=AndroidHttpClient.newInstance("");
        HttpGet httpGet=new HttpGet(url);

        try {
            HttpResponse httpResponse=androidHttpClient.execute(httpGet);

            HttpEntity httpEntity=httpResponse.getEntity();
            is=httpEntity.getContent();

            int statusCode=httpResponse.getStatusLine().getStatusCode();
            if (statusCode==200){
                //创建包装流
                br=new BufferedReader(new InputStreamReader(is));
                //定义String类型用于存储单行数据
                String line=null;
                //创建StringBuffer对象用于存储所有数据

                while ((line=br.readLine())!=null){
                    sb.append(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}

 

网络取数据封装的类:

package com.scxh.htmlandhttp;

import android.app.Activity;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.scxh.R;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Administrator on 15-1-7.
 */
public class HttpActivity extends Activity {
    private String httpPath="http://192.168.1.154:8080/web/demoservlet";
    private String baidu="http://www.baidu.com/";
    private Button httpBtn,packageBtn;
    private TextView httpTv;
    private EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http);
        editText=(EditText)findViewById(R.id.httpEditeText);
        httpBtn=(Button)findViewById(R.id.httpButton);

        httpTv=(TextView)findViewById(R.id.httpTextView);

        httpBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
             new AsyncTask<String,Void,String>(){
                 @Override
                 protected String doInBackground(String... strings) {
                     String httpUrl=strings[0];
                     /*调用获取网络数据的方法*/
                     String content= null;
                     try {
                         content = getApacheData(httpUrl);
                     } catch (UnsupportedEncodingException e) {
                         e.printStackTrace();
                     }
                     return content;
                 }

                 @Override
                 protected void onPostExecute(String s) {
                     httpTv.setText(s);
                 }
             }.execute(editText.getText().toString());
            }
        });

    }
    /*利用封装好类,来获取网络数据*/
    public void packageButton(View view){
        HttpIntentPackage.HttpConnectInterface httpConnectInterface=new HttpIntentPackage.HttpConnectInterface() {
            @Override
            public void execute(String result) {
                httpTv.setText(result);
            }
        };
        HashMap<String,String> parameters=new HashMap<String, String>();
        parameters.put("userName","陈刚");
        parameters.put("passWord","表演节目");
    /*利用Json传输数据*/
        JSONObject jsonObject=new JSONObject(parameters);
        String json=jsonObject.toString();
        HashMap<String,String> param=new HashMap<String, String>();
        param.put("jsonStr",json);
    /*利用Json传输数据*/

        HttpIntentPackage httpIntentPackage=new HttpIntentPackage();
        httpIntentPackage.asyncConnect(httpPath,
                HttpIntentPackage.HttpMethod.POST,param);
        httpIntentPackage.setmHttpConnectInterface(httpConnectInterface);
    }
    /*实现客服端与服务端的链接*/
    /*用JAVA从网络获取数据*/
    private String getIntentData(String url){
        InputStream is=null;
        BufferedReader br=null;
        StringBuffer sb = null;
        HttpURLConnection connection=null;
        try {
            //封装访问服务器地址
            URL url1=new URL(url);
            //打开对服务器的链接
            connection=(HttpURLConnection)url1.openConnection();

            connection.setRequestMethod("GET");//利用GET方法取数据
            //链接服务器
            connection.connect();
            //得到输入流
            is=connection.getInputStream();
            //创建包装流
            br=new BufferedReader(new InputStreamReader(is));
            //定义String类型用于存储单行数据
            String line=null;
            //创建StringBuffer对象用于存储所有数据
            sb=new StringBuffer();
            while ((line=br.readLine())!=null){
                sb.append(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            connection.disconnect();
            if (br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
    /*利用apache获取网络数据*/
    private String getApacheData(String url) throws UnsupportedEncodingException {
        InputStream is=null;
        BufferedReader br=null;
        StringBuffer sb = new StringBuffer();
        HttpClient httpClient=new DefaultHttpClient();
        HttpPost httpPost=new HttpPost(url);
        /*利用post传参152-162*/
 /*       BasicNameValuePair userNamePair=new BasicNameValuePair("userName","四川新华");
        Log.e("userNamePair",userNamePair+"");

        BasicNameValuePair passWordPair=new BasicNameValuePair("passWord","12315");
        Log.e("passWordPair",passWordPair+"");
        ArrayList<BasicNameValuePair> arrayList=new ArrayList<BasicNameValuePair>();
        arrayList.add(userNamePair);
        arrayList.add(passWordPair);

        UrlEncodedFormEntity entity=new UrlEncodedFormEntity(arrayList,HTTP.UTF_8);
        httpPost.setEntity(entity);*/
        try {
            HttpResponse httpResponse=httpClient.execute(httpPost);
            HttpEntity httpEntity=httpResponse.getEntity();
            is=httpEntity.getContent();

            int statusCode=httpResponse.getStatusLine().getStatusCode();
            if (statusCode==200){
                //创建包装流
                br=new BufferedReader(new InputStreamReader(is));
                //定义String类型用于存储单行数据
                String line=null;
                //创建StringBuffer对象用于存储所有数据
                sb=new StringBuffer();
                while ((line=br.readLine())!=null){
                    sb.append(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sb.toString();
    }
    /*利用安卓方法获取数据*/
    private String getAndroidData(String url){
        InputStream is=null;
        BufferedReader br=null;
        StringBuffer sb=new StringBuffer();
        AndroidHttpClient androidHttpClient=AndroidHttpClient.newInstance("");
        HttpGet httpGet=new HttpGet(url);

        try {
            HttpResponse httpResponse=androidHttpClient.execute(httpGet);

            HttpEntity httpEntity=httpResponse.getEntity();
            is=httpEntity.getContent();

            int statusCode=httpResponse.getStatusLine().getStatusCode();
            if (statusCode==200){
                //创建包装流
                br=new BufferedReader(new InputStreamReader(is));
                //定义String类型用于存储单行数据
                String line=null;
                //创建StringBuffer对象用于存储所有数据

                while ((line=br.readLine())!=null){
                    sb.append(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值