Android网络通讯之HTTP请求通信(一)

来源:互联网 发布:sql获取表的所有字段 编辑:程序博客网 时间:2024/05/16 06:58

Android网络通讯平台支持还是比较丰富的,除了兼容J2ME中的java.net api外还提供了一下Android平台独有的类android.net这个Package。似乎更强大的是org.apache.http类,这个是apache实验室开源的包,对于Http请求处理很方便。

java.net 与android.net 用法基本相同,下面主要用两个例子来介绍一下
一种是GET方式,一种是POST方式。然后介绍HttpClient的Get/Post方式方式

 

布局文件很简单,我用的都是同一个,一个TextView控件,一个Button控件.点击Button处理Http请求.

java代码如下:

 

package com.test.helloworld;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;


public class Activity01 extends Activity {
 
 private final String DEBUG_TAG = "System.out";
 
 private TextView mTextView ;
 private Button mButton;
 
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.http);
  
  mTextView = (TextView)findViewById(R.id.TextView01);
  mButton = (Button)findViewById(R.id.Button01);
  mButton.setOnClickListener(new httpListener());
 }
 
 //设置按钮监听器
 class httpListener implements OnClickListener{
  public void onClick(View v) {
   refresh();
  }
 }

 private void refresh(){
  String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";
  //URL可以加参数
  //String httpUrl = "http://192.168.0.101:8080/Test/test.jsp?par=abcdefg";
  String resultData = "";
  URL url = null;
  try{
   //创建一个URL对象
   url = new URL(httpUrl);
  }catch(MalformedURLException e){
   Log.d(DEBUG_TAG, "create URL Exception");
  }
  //声明HttpURLConnection对象
  HttpURLConnection urlConn = null;
  //声明InputStreamReader对象
  InputStreamReader in = null;
  //声明BufferedReader对象
  BufferedReader buffer = null;
  String inputLine = null;
  if(url != null){
   try{
    //使用HttpURLConnection打开连接
    urlConn = (HttpURLConnection) url.openConnection();
    //得到读取的内容(流)
    in = new InputStreamReader(urlConn.getInputStream());
    //创建BufferReader对象,输出时候用到
    buffer = new BufferedReader(in);
    //使用循环来读取数据
    while ((inputLine = buffer.readLine()) != null) {
     //在每一行后面加上换行
     resultData += inputLine + "\n";
    }
    //设置显示取的的内容
    if(resultData != null && !resultData.equals("")){
     mTextView.setText(resultData);
    }else{
     mTextView.setText("读取的内容为空");
    }
   }catch(IOException e){
    e.printStackTrace();
   }finally{
    try {
     //关闭InputStreamReader
     in.close();
     //关闭URL连接
     urlConn.disconnect();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }else{
   Log.d(DEBUG_TAG, "URL is NULL");
  }
 }
}

0 0
原创粉丝点击