HTTP

package com.yanjun;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
   /** Called when the activity is first created. */
  Button button = null;
   // 服务器端接收请求后返回的响应----httpResponse
  HttpResponse httpResponse;
   // httpEntity代表接收的http消息
  HttpEntity httpEntity = null;


  @Override
   public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    button = (Button) findViewById(R.id.button1);
    button.setOnClickListener( new OnClickListener() {

       public void onClick(View v) {
         // 首先,生成一个请求对象---HttpGet,参数为请求的网址即URL
        HttpGet httpGet = new HttpGet( "http://www.baidu.com/");
        // 生成一个HTTP客户端对象----HttpClient
        HttpClient httpClient = new DefaultHttpClient();
        // 使用HTTP客户端发送请求对象
        // 得到服务器端发送响应的内容---通过inputStream
        InputStream inputStream = null;
        try {
          // 服务器端发送的响应----httpResponse
          httpResponse = httpClient.execute(httpGet);
          // 服务器端发送响应的内容---httpEntity
          httpEntity = httpResponse.getEntity();
          // 得到服务器端发送响应的内容---通过inputStream
          inputStream = httpEntity.getContent();
          // IO流的操作
          BufferedReader bufferedReader = new BufferedReader(
              new InputStreamReader(inputStream));
          String result = "";
          String line = "";
          while ((line = bufferedReader.readLine()) != null) {
            result = result + line;
          }
          System.out.println(result);

        } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } finally {
          try {
            inputStream.close();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }

      }
    });
  }
}
 

注意权限

Http两种请求的特点----Httpget和HttpPost
get请求和post请求的区别在于:
get在向服务器端发送数据的时候需要在URL后加上?+键值对&键值对
post在向服务器端发送数据时:如果需要发送键值对数据时要使用NameValurPair对象添加数据,然后在放进list对象里去,然后通过 httpEntity 对象把list放进去,再将 httpEntity 对象放到httppost里面,httppost里面直接写URL即可
 
详细代码参看Mars老师的android视频,第四季Http(三)。
 

你可能感兴趣的:(http)