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.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之间的跳转示例上修改的。
更多相关文章
- Android ApiDemos示例解析(8):App->Activity->Hello world
- 跟着第二行代码回顾Android--持久化技术
- Android常用三栏式滑动/滚动视图(View)的设计与实现代码
- Android Http请求的代码
- Android 源代码编后的目录分析
- 代码混淆
- PendingIntent实现原理和代码
- Eclipse For Android 代码自动提示功能