zoukankan      html  css  js  c++  java
  • Android与服务器http连接模块代码

    
    
      1 package com.example.httpdemo2;
      2 
      3 import java.io.BufferedReader;
      4 import java.io.IOException;
      5 import java.io.InputStream;
      6 import java.io.InputStreamReader;
      7 import java.io.UnsupportedEncodingException;
      8 import java.util.ArrayList;
      9 import java.util.List;
     10 
     11 import org.apache.http.HttpEntity;
     12 import org.apache.http.HttpResponse;
     13 import org.apache.http.NameValuePair;
     14 import org.apache.http.client.HttpClient;
     15 import org.apache.http.client.entity.UrlEncodedFormEntity;
     16 import org.apache.http.client.methods.HttpGet;
     17 import org.apache.http.client.methods.HttpPost;
     18 import org.apache.http.impl.client.DefaultHttpClient;
     19 import org.apache.http.message.BasicNameValuePair;
     20 
     21 import android.os.Bundle;
     22 import android.app.Activity;
     23 import android.util.Log;
     24 import android.view.Menu;
     25 import android.view.View;
     26 import android.view.View.OnClickListener;
     27 import android.widget.Button;
     28 import android.widget.EditText;
     29 import android.widget.TextView;
     30 
     31 public class HttpDemo2Activity extends Activity
     32 {
     33     private String TAG = "http";
     34     private EditText mNameText = null;
     35     private EditText mAgeText = null;
     36 
     37     private Button getButton = null;
     38     private Button postButton = null;
     39 
     40     private TextView mResult = null;
     41 
     42     // 基本地址:服务器ip地址:端口号/Web项目逻辑地址+目标页面(Servlet)的url-pattern
     43     private String baseURL = "http://192.168.11.6:8080/HelloWeb/servlet/WelcomeUserServlet";
     44 
     45     @Override
     46     protected void onCreate(Bundle savedInstanceState)
     47     {
     48         Log.i(TAG, "onCreate");
     49         super.onCreate(savedInstanceState);
     50         setContentView(R.layout.activity_http_demo2);
     51 
     52         mNameText = (EditText) findViewById(R.id.name);
     53         mAgeText = (EditText) findViewById(R.id.age);
     54         mResult = (TextView) findViewById(R.id.result);
     55 
     56         getButton = (Button) findViewById(R.id.submit_get);
     57         getButton.setOnClickListener(mGetClickListener);
     58         postButton = (Button) findViewById(R.id.submit_post);
     59         postButton.setOnClickListener(mPostClickListener);
     60     }
     61 
     62     private OnClickListener mGetClickListener = new View.OnClickListener()
     63     {
     64 
     65         @Override
     66         public void onClick(View v)
     67         {
     68             Log.i(TAG, "GET request");
     69             // 先获取用户名和年龄
     70             String name = mNameText.getText().toString();
     71             String age = mAgeText.getText().toString();
     72 
     73             // 使用GET方法发送请求,需要把参数加在URL后面,用?连接,参数之间用&分隔
     74             String url = baseURL + "?username=" + name + "&age=" + age;
     75 
     76             // 生成请求对象
     77             HttpGet httpGet = new HttpGet(url);
     78             HttpClient httpClient = new DefaultHttpClient();
     79 
     80             // 发送请求
     81             try
     82             {
     83 
     84                 HttpResponse response = httpClient.execute(httpGet);
     85 
     86                 // 显示响应
     87                 showResponseResult(response);// 一个私有方法,将响应结果显示出来
     88 
     89             }
     90             catch (Exception e)
     91             {
     92                 e.printStackTrace();
     93             }
     94 
     95         }
     96     };
     97 
     98     private OnClickListener mPostClickListener = new View.OnClickListener()
     99     {
    100 
    101         @Override
    102         public void onClick(View v)
    103         {
    104             Log.i(TAG, "POST request");
    105             // 先获取用户名和年龄
    106             String name = mNameText.getText().toString();
    107             String age = mAgeText.getText().toString();
    108 
    109             NameValuePair pair1 = new BasicNameValuePair("username", name);
    110             NameValuePair pair2 = new BasicNameValuePair("age", age);
    111 
    112             List<NameValuePair> pairList = new ArrayList<NameValuePair>();
    113             pairList.add(pair1);
    114             pairList.add(pair2);
    115 
    116             try
    117             {
    118                 HttpEntity requestHttpEntity = new UrlEncodedFormEntity(
    119                         pairList);
    120                 // URL使用基本URL即可,其中不需要加参数
    121                 HttpPost httpPost = new HttpPost(baseURL);
    122                 // 将请求体内容加入请求中
    123                 httpPost.setEntity(requestHttpEntity);
    124                 // 需要客户端对象来发送请求
    125                 HttpClient httpClient = new DefaultHttpClient();
    126                 // 发送请求
    127                 HttpResponse response = httpClient.execute(httpPost);
    128                 // 显示响应
    129                 showResponseResult(response);
    130             }
    131             catch (Exception e)
    132             {
    133                 e.printStackTrace();
    134             }
    135 
    136         }
    137     };
    138 
    139     /**
    140      * 显示响应结果到命令行和TextView
    141      * @param response
    142      */
    143     private void showResponseResult(HttpResponse response)
    144     {
    145         if (null == response)
    146         {
    147             return;
    148         }
    149 
    150         HttpEntity httpEntity = response.getEntity();
    151         try
    152         {
    153             InputStream inputStream = httpEntity.getContent();
    154             BufferedReader reader = new BufferedReader(new InputStreamReader(
    155                     inputStream));
    156             String result = "";
    157             String line = "";
    158             while (null != (line = reader.readLine()))
    159             {
    160                 result += line;
    161 
    162             }
    163 
    164             System.out.println(result);
    165             mResult.setText("Response Content from server: " + result);
    166         }
    167         catch (Exception e)
    168         {
    169             e.printStackTrace();
    170         }
    171 
    172     }
    173 
    174 }

    布局文件:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Username:" />
    
    <EditText
    android:id="@+id/name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="text" />
    
    <TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="User Age:" />
    
    <EditText
    android:id="@+id/age"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="number" />
    
    <Button
    android:id="@+id/submit_get"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Submit using GET" />
    
    <Button
    android:id="@+id/submit_post"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Submit using POST" />
    
    <TextView
    android:id="@+id/result"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="#0000FF"
    android:textSize="14sp" >
    </TextView>
    
    </LinearLayout>
    
     

    须在androidMenifest中配置联网权限;

  • 相关阅读:
    第一个博客——python通过值传递函数参数
    JAVA并发体系-1.1-终结任务或线程
    JAVA并发体系-1.4-线程池
    JAVA并发体系-1.3-线程之间的协作
    JAVA并发体系-2-锁机制
    并发实现机制-1-综述
    JAVA并发体系-3-并发容器
    并发实现机制-2-互斥实现
    并发实现机制-3-死锁和饥饿
    JAVA持有对象
  • 原文地址:https://www.cnblogs.com/yjpjy/p/5103046.html
Copyright © 2011-2022 走看看