android编写访问http的代码

android使用apache httpclient项目实现手机做为http客户端的调用。android使用的是最新的httpclient 4.0版本,网上不少国内的文档是3.x的,调用方式不同。html

httpclient有一个官方教程,见:java

http://hc.apache.org/httpcomponents-client/tutorial/html/android

httpclient的javadoc,见:apache

http://hc.apache.org/httpcomponents-client/httpclient/apidocs/overview-summary.htmlapi

可在activivy中直接调用httpclient作对服务器端的访问,如下是一个简单的示例代码:服务器

package com.easymorse;app

import java.io.BufferedReader;
import java.io.InputStreamReader;ide

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;this

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;component

public class NextActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.next_activity);

        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(“http://marshal.easymorse.com/”);
        try {
            HttpResponse response = client.execute(get);
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
            for (String s = reader.readLine(); s != null; s = reader.readLine()) {
                Log.v(“response”, s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

代码是在实现android activity之间的跳转示例上修改的。

相关文章
相关标签/搜索