现在的位置: 首页 > 综合 > 正文

Android HttpClient网络通信

2013年04月20日 ⁄ 综合 ⁄ 共 13172字 ⁄ 字号 评论关闭

view plaincopy to clipboardprint?
01.<?xml version="1.0" encoding="utf-8"?>  
02.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android
03.    android:orientation="vertical" android:layout_width="fill_parent" 
04.    android:layout_height="fill_parent">  
05.    <Button android:text="GET" android:id="@+id/Button01" 
06.        android:layout_width="fill_parent" 
07.        android:layout_height="wrap_content">  
08.    </Button>  
09.    <Button android:text="POST" android:id="@+id/Button02" 
10.        android:layout_width="fill_parent" 
11.        android:layout_height="wrap_content">  
12.    </Button>  
13.    <TextView android:id="@+id/TextView" android:layout_width="fill_parent" 
14.        android:layout_height="wrap_content"/>  
15.</LinearLayout> 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">
 <Button android:text="GET" android:id="@+id/Button01"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
 </Button>
 <Button android:text="POST" android:id="@+id/Button02"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
 </Button>
 <TextView android:id="@+id/TextView" android:layout_width="fill_parent"
  android:layout_height="wrap_content"/>
</LinearLayout>

view plaincopy to clipboardprint?
01.package com.Aina.Android;  
02. 
03.import java.io.BufferedReader;  
04.import java.io.IOException;  
05.import java.io.InputStream;  
06.import java.io.InputStreamReader;  
07.import java.io.UnsupportedEncodingException;  
08.import java.net.HttpURLConnection;  
09.import java.net.MalformedURLException;  
10.import java.net.URL;  
11. 
12.import java.util.ArrayList;  
13.import java.util.List;  
14. 
15.import org.apache.http.HttpEntity;  
16.import org.apache.http.HttpResponse;  
17.import org.apache.http.HttpStatus;  
18.import org.apache.http.NameValuePair;  
19.import org.apache.http.client.ClientProtocolException;  
20.import org.apache.http.client.HttpClient;  
21.import org.apache.http.client.entity.UrlEncodedFormEntity;  
22.import org.apache.http.client.methods.HttpGet;  
23.import org.apache.http.client.methods.HttpPost;  
24.import org.apache.http.impl.client.DefaultHttpClient;  
25.import org.apache.http.message.BasicNameValuePair;  
26.import org.apache.http.util.EntityUtils;  
27. 
28.import android.app.Activity;  
29.import android.os.Bundle;  
30.import android.os.Handler;  
31.import android.os.Message;  
32.import android.view.View;  
33.import android.widget.Button;  
34.import android.widget.TextView;  
35. 
36.public class Test extends Activity implements Runnable{  
37.    /** Called when the activity is first created. */ 
38.    private Button btn_get = null;  
39.    private Button btn_post = null;  
40.    private TextView tv_rp = null;  
41.    @Override 
42.    public void onCreate(Bundle savedInstanceState) {  
43.        super.onCreate(savedInstanceState);  
44.        setContentView(R.layout.main);  
45.        btn_get = (Button) this.findViewById(R.id.Button01);  
46.        btn_post = (Button) this.findViewById(R.id.Button02);  
47.        tv_rp = (TextView) this.findViewById(R.id.TextView);  
48.        btn_get.setOnClickListener(new Button.OnClickListener(){  
49. 
50.            public void onClick(View v) {  
51.                // TODO Auto-generated method stub  
52.                String httpUrl = "http://192.168.0.132:8080/Android/httpreq.jsp?par=request-get";  
53.                HttpGet request = new HttpGet(httpUrl);  
54.                HttpClient httpClient = new DefaultHttpClient();  
55.                try {  
56.                    HttpResponse response = httpClient.execute(request);  
57.                    if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){  
58.                        String str = EntityUtils.toString(response.getEntity());  
59.                        tv_rp.setText(str);  
60.                    }else{  
61.                        tv_rp.setText("请求错误");  
62.                    }   
63.                } catch (ClientProtocolException e) {  
64.                    // TODO Auto-generated catch block  
65.                    e.printStackTrace();      
66.                } catch (IOException e) {  
67.                    // TODO Auto-generated catch block  
68.                    e.printStackTrace();  
69.                }  
70.            }  
71.              
72.        });  
73.        btn_post.setOnClickListener(new Button.OnClickListener(){  
74. 
75.            public void onClick(View v) {  
76.                // TODO Auto-generated method stub  
77.                String httpUrl = "http://192.168.0.132:8080/Android/httpreq.jsp";  
78.                HttpPost request = new HttpPost(httpUrl);  
79.                List<NameValuePair> params = new ArrayList<NameValuePair>();  
80.                params.add(new BasicNameValuePair("par","request-post"));  
81.                try {  
82.                    HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");  
83.                    request.setEntity(entity);  
84.                    HttpClient client = new DefaultHttpClient();  
85.                    HttpResponse response = client.execute(request);  
86.                    if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){  
87.                        String str = EntityUtils.toString(response.getEntity());  
88.                        tv_rp.setText(str);  
89.                    }else{  
90.                        tv_rp.setText("请求错误");  
91.                    }  
92.                } catch (UnsupportedEncodingException e) {  
93.                    // TODO Auto-generated catch block  
94.                    e.printStackTrace();  
95.                } catch (ClientProtocolException e) {  
96.                    // TODO Auto-generated catch block  
97.                    e.printStackTrace();  
98.                } catch (IOException e) {  
99.                    // TODO Auto-generated catch block  
100.                    e.printStackTrace();  
101.                }  
102.            }  
103.              
104.        });  
105.        new Thread(this).start();  
106.    }  
107.    public void refresh(){  
108.        String httpUrl = "http://192.168.0.132:8080/Android/httpreq.jsp";  
109.        try {  
110.            URL url = new URL(httpUrl);  
111.            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
112.            urlConn.connect();  
113.            InputStream input = urlConn.getInputStream();  
114.            InputStreamReader inputreader = new InputStreamReader(input);  
115.            BufferedReader reader = new BufferedReader(inputreader);  
116.            String str = null;  
117.            StringBuffer sb = new StringBuffer();  
118.            while((str = reader.readLine())!= null){  
119.                sb.append(str).append("/n");  
120.            }  
121.            if(sb != null){  
122.                tv_rp.setText(sb.toString());  
123.            }else{  
124.                tv_rp.setText("NULL");  
125.            }  
126.            reader.close();  
127.            inputreader.close();  
128.            input.close();  
129.            reader = null;  
130.            inputreader = null;  
131.            input = null;  
132.        } catch (MalformedURLException e) {  
133.            e.printStackTrace();  
134.        } catch (IOException e) {  
135.            // TODO Auto-generated catch block  
136.            e.printStackTrace();  
137.        }  
138.    }  
139.    public Handler handler = new Handler(){  
140.        public void handleMessage(Message msg){  
141.            super.handleMessage(msg);  
142.            refresh();  
143.        }  
144.    };  
145.    public void run() {  
146.        // TODO Auto-generated method stub  
147.        while(true){  
148.            try {  
149.                Thread.sleep(1000);  
150.                handler.sendMessage(handler.obtainMessage());  
151.            } catch (InterruptedException e) {  
152.                // TODO Auto-generated catch block  
153.                e.printStackTrace();  
154.            }  
155.        }  
156.    }  
157.} 
package com.Aina.Android;

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

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Test extends Activity implements Runnable{
    /** Called when the activity is first created. */
 private Button btn_get = null;
 private Button btn_post = null;
 private TextView tv_rp = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn_get = (Button) this.findViewById(R.id.Button01);
        btn_post = (Button) this.findViewById(R.id.Button02);
        tv_rp = (TextView) this.findViewById(R.id.TextView);
        btn_get.setOnClickListener(new Button.OnClickListener(){

   public void onClick(View v) {
    // TODO Auto-generated method stub
    String httpUrl = "http://192.168.0.132:8080/Android/httpreq.jsp?par=request-get";
    HttpGet request = new HttpGet(httpUrl);
    HttpClient httpClient = new DefaultHttpClient();
    try {
     HttpResponse response = httpClient.execute(request);
     if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
      String str = EntityUtils.toString(response.getEntity());
      tv_rp.setText(str);
     }else{
      tv_rp.setText("请求错误");
     }
    } catch (ClientProtocolException e) {
     // TODO Auto-generated catch block
     e.printStackTrace(); 
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
         
        });
        btn_post.setOnClickListener(new Button.OnClickListener(){

   public void onClick(View v) {
    // TODO Auto-generated method stub
    String httpUrl = "http://192.168.0.132:8080/Android/httpreq.jsp";
    HttpPost request = new HttpPost(httpUrl);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("par","request-post"));
    try {
     HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
     request.setEntity(entity);
     HttpClient client = new DefaultHttpClient();
     HttpResponse response = client.execute(request);
     if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
      String str = EntityUtils.toString(response.getEntity());
      tv_rp.setText(str);
     }else{
      tv_rp.setText("请求错误");
     }
    } catch (UnsupportedEncodingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (ClientProtocolException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
         
        });
        new Thread(this).start();
    }
    public void refresh(){
     String httpUrl = "http://192.168.0.132:8080/Android/httpreq.jsp";
     try {
   URL url = new URL(httpUrl);
   HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
   urlConn.connect();
   InputStream input = urlConn.getInputStream();
   InputStreamReader inputreader = new InputStreamReader(input);
   BufferedReader reader = new BufferedReader(inputreader);
   String str = null;
   StringBuffer sb = new StringBuffer();
   while((str = reader.readLine())!= null){
    sb.append(str).append("/n");
   }
   if(sb != null){
    tv_rp.setText(sb.toString());
   }else{
    tv_rp.setText("NULL");
   }
   reader.close();
   inputreader.close();
   input.close();
   reader = null;
   inputreader = null;
   input = null;
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
    }
    public Handler handler = new Handler(){
     public void handleMessage(Message msg){
      super.handleMessage(msg);
      refresh();
     }
    };
 public void run() {
  // TODO Auto-generated method stub
  while(true){
   try {
    Thread.sleep(1000);
    handler.sendMessage(handler.obtainMessage());
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}

 
view plaincopy to clipboardprint?
01.<?xml version="1.0" encoding="utf-8"?> 
02.<manifest xmlns:android="http://schemas.android.com/apk/res/android
03.      package="com.Aina.Android" 
04.      android:versionCode="1" 
05.      android:versionName="1.0"> 
06.    <application android:icon="@drawable/icon" android:label="@string/app_name"> 
07.        <activity android:name=".Test" 
08.                  android:label="@string/app_name"> 
09.            <intent-filter> 
10.                <action android:name="android.intent.action.MAIN" /> 
11.                <category android:name="android.intent.category.LAUNCHER" /> 
12.            </intent-filter> 
13.        </activity> 
14. 
15.    </application> 
16.<uses-permission android:name="android.permission.INTERNET" /> 
17. 
18.</manifest>  

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/xiangyong2008/archive/2010/09/02/5859864.aspx

抱歉!评论已关闭.