android 通过http访问服务器数据

android 访问数据有一下几种方式:

1:Buddle。不是持久化

2:sharedpreshared:是持久化的。一般用于小型数据。

3:sqlite:数据库,用于数据量较大的持久化数据。

4:sdcard。

5:http:服务器数据访问。

主要介绍一下第5个:http。

http:访问我知道的有一下几种方法:

1.直接通过url链接服务器,通过url.openStream()来获得输入流InputStream。

这种方法要新建线程,不能直接在主线程ui中实用。

* 创建handler。

* 创建runnable。启动线程thread.start

* 在runnable中重新run,获取输入流InputStream。

通过url调用本地web服务器一张图片。注意android访问本地服务器的地址:10.0.2.2不是127.0.0.1

 package com.example.test;

import java.io.InputStream;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {
    private ImageView imageView;
    String resultString = "";
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Handler handler;
        imageView = (ImageView) findViewById(R.id.show);

        /* handler 主要 */
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                
                switch (msg.what) {
                case 0:
                    Bitmap bitmap = (Bitmap) msg.obj;
                    imageView.setImageBitmap(bitmap);
                    break;        

                default:
                    break;
                }

            }

        };
        /* runnable接口  主要*/
        Runnable my = new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = null;
                URL url;

                try {
                    url = new URL(
                            "http://10.0.2.2:8080/hello/source/image/2.jpg");
                    InputStream is = url.openStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    is.close();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {

                }

                Message msg = new Message();
                msg.what = 0;
                msg.obj = bitmap;
                handler.sendMessage(msg);

            }
        };
     /*主要*/
        Thread thread = new Thread(my);
        thread.start();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, 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);
    }
}

2.通过Java的HttpURLConnection和Apache的HttpClient。

他们之间的用法基本一样。HttpClient是HttpURLConnection的更高版本,HttpURLConnection能实现的功能,httpclient都能实现。httpclient有些功能HttpURLConnection不能实现。如一些需要登录的页面数据HttpURLConnection不能直接访问得到数据,而httpclient可以直接。这点如果不明白,可以先看一下李刚的《疯狂android讲义》有说明。但是好像google更推荐实用HttpURLConnection。可以看一下这里:http://blog.csdn.net/huzgd/article/details/8712187

HttpClient的基本用法:

HttpClient client 生成一个http客户端发送请求对象

HttpPost和HttpGet请求方式

httpResponse = client.execute(httpPost)  发出请求并得到结果


HttpEntity entity = httpResponse.getEntity();  获取响应里面的内容

entity.tostring 得到字符串。


package com.example.test1;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.R.string;
import android.content.Entity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.HttpGet;

public class MainActivity extends ActionBarActivity {
	TextView textView;
	ImageView imageView;
	Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		imageView = (ImageView) findViewById(R.id.imageView1);
		textView = (TextView)findViewById(R.id.textView1);
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch (msg.what) {
				case 0:
					String string = (String) msg.obj;
					textView.setText(string);
					break;

				default:
					break;
				}
			}

		};

		Runnable my = new Runnable() {

			@Override
			public void run() {
				Message msg = new Message();
				msg.what = 0;
				

				try {
					String url = "http://10.0.2.2:8080/hello/test.json";
					HttpGet request = new HttpGet(url);
					DefaultHttpClient client = new DefaultHttpClient();
					HttpResponse response = client.execute(request);
					String string  = EntityUtils.toString(response.getEntity(), "gbk");	
					msg.obj = string;
					handler.sendMessage(msg);
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				

			}
		};
		Thread thread = new Thread(my);
		thread.start();

		/*
		 * TwitterRestClient.get("image/2.jpg", null, new
		 * AsyncHttpResponseHandler() {
		 * 
		 * @Override public void onRetry(int retryNo) { // TODO Auto-generated
		 * method stub super.onRetry(retryNo); }
		 * 
		 * @Override public void onStart() { // TODO Auto-generated method stub
		 * super.onStart();
		 * 
		 * }
		 * 
		 * @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2)
		 * {
		 * 
		 * Bitmap bitmap = BitmapFactory.decodeByteArray(arg2, 0, arg2.length);
		 * imageView.setImageBitmap(bitmap); }
		 * 
		 * @Override public void onFailure(int arg0, Header[] arg1, byte[] arg2,
		 * Throwable arg3) { Log.v("http", "ERROR");
		 * 
		 * } });
		 */
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, 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);
	}
}
3.上两种可以多看看别人的博客就可以完成了。还有一种更简单及时第三方库android-async-http。只需两部就可以了。


一,创建请求对象

AsyncHttpClient client = new AsyncHttpClient();
二。选择方式访问 get、put、post、head、delete



client.get("http://www.google.com", new AsyncHttpResponseHandler() {
    @Override public void onSuccess(String response) {
        System.out.println(response);
    }
});
很简单吧。这里不用创建线程,直接用就可以了。




AsyncHttpClient client = new AsyncHttpClient();
client.get("https://www.baidu.com", new AsyncHttpResponseHandler() {

    @Override
    public void onStart() {
        // called before request is started
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
        // called when response HTTP status is "200 OK"
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
        // called when response HTTP status is "4XX" (eg. 401, 403, 404)
    }

    @Override
    public void onRetry(int retryNo) {
        // called when request is retried
	}
});
一般需要重写onsuccess方法。 官方文档很详细还有一篇 博客也很好。

官方推荐了一种静态方法,感觉他更方便访问数据,只要你把资源名就行了。

1.先把原来的方法和路径包装起来:

import com.loopj.android.http.*;

public class TwitterRestClient {
  private static final String BASE_URL = "https://api.twitter.com/1/";

  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}
在按原来的方法实用,只是要用上面的包装类

import org.json.*;
import com.loopj.android.http.*;

class TwitterRestClientUsage {
    public void getPublicTimeline() throws JSONException {
        TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                // If the response is JSONObject instead of expected JSONArray
            }
            
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
                // Pull out the first event on the public timeline
                JSONObject firstEvent = timeline.get(0);
                String tweetText = firstEvent.getString("text");

                // Do something with the response
                System.out.println(tweetText);
            }
        });
    }
}





转载于:https://my.oschina.net/liuxinquan/blog/491986

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值