android编写访问http的代码

本文介绍如何使用 Android 上的 HttpClient 4.0 版本来实现 HTTP 客户端的功能,包括发送 GET 请求并读取服务器响应。提供了一个实际的代码示例,展示了如何在 Activity 中集成 HttpClient 并进行基本的网络请求。

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

httpclient有一个官方教程,见:

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

httpclient的javadoc,见:

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

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

package com.easymorse;

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

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;

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

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之间的跳转示例上修改的。

转载于:https://my.oschina.net/xiahuawuyu/blog/71092

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值