android编写访问http的代码

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.rbf.httpclienttest;

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.widget.EditText;

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

public class HTTPClientTestActivity extends Activity {
    EditText et;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        et = (EditText)findViewById(R.id.ev);
        HttpClient hc = new DefaultHttpClient();
        HttpGet get = new HttpGet("http://marshal.easymorse.com/");
        try {
            HttpResponse hr = hc.execute(get);
            BufferedReader br = new BufferedReader(new InputStreamReader((hr.getEntity().getContent())));
           
            StringBuilder holder = new StringBuilder();
            for(String str = br.readLine(); str != null; str = br.readLine()) {
                holder.append(str);
            }
            et.setText(holder);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



注意 AndroidManifest.xml中要开启应用访问网络的权限:

  <uses-permission android:name="android.permission.INTERNET" />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值