码迷,mamicode.com
首页 > 移动开发 > 详细

使用Apache HttpClient访问网络(实现手机端注册,服务器返回信息)

时间:2015-11-06 23:40:49      阅读:610      评论:0      收藏:0      [点我收藏+]

标签:网络编程   服务器   运行图   客户端   手机   httpclient   

这两天看了点网络编程,根据教程写了一个小的注册服务,贴出来。


本实例分别演示用GET方式和POST方式想服务器发送注册信息,分为客户端和服务器端两部分:

  1. 客户端注册用户信息,发送到服务器

  2. 服务器端接收信息并向客户端返回注册信息。(服务器端使用J2EE中的Servlet技术来实现,并发布到Tomcat服务器上)



代码运行效果如下:


客户端:

技术分享


1.点击get注册按钮后:


客户端:

技术分享


服务器端:

技术分享


2.点击post注册按钮后:


客户端:


技术分享


服务器端:

技术分享



3.当服务器端关闭时:


技术分享

客户端注册信息时会提示链接超时:


技术分享




这就是完整的运行图,下面给出完整代码和代码注释:



客户端代码:


1.activity_main.xml代码:


<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"

    tools:context=".MainActivity" >


    <TextView android:layout_width="fill_parent"

android:layout_height="wrap_content" 

android:text="账户"

android:layout_marginTop="5.0dip" 

android:layout_marginLeft="5.0dip"

android:layout_marginRight="5.0dip" 

android:textStyle="bold"

android:textAppearance="?android:textAppearanceMedium" />


<EditText android:id="@+id/username"

android:layout_width="fill_parent" 

android:layout_height="wrap_content"

android:layout_marginTop="5.0dip" 

android:layout_marginLeft="5.0dip"

android:layout_marginRight="5.0dip" />


<TextView android:layout_width="fill_parent"

android:layout_height="wrap_content" 

android:text="密码"

android:layout_marginTop="5.0dip" 

android:layout_marginLeft="5.0dip"

android:layout_marginRight="5.0dip" 

android:textStyle="bold"

android:textAppearance="?android:textAppearanceMedium" />


<EditText android:id="@+id/password" 

   android:layout_width="fill_parent"

android:layout_height="wrap_content" 

android:layout_marginTop="5.0dip"

android:layout_marginLeft="5.0dip" 

android:layout_marginRight="5.0dip" />


<LinearLayout android:orientation="horizontal"

android:layout_width="fill_parent" 

android:layout_height="wrap_content">


<Button android:id="@+id/button_get" 

   android:layout_width="wrap_content"

android:layout_height="wrap_content" 

android:layout_marginTop="5.0dip"

android:layout_marginLeft="5.0dip" 

android:layout_marginRight="5.0dip"

android:layout_weight="1.0" 

android:text="get注册" />


<Button 

   android:id="@+id/button_post"

android:layout_width="wrap_content" 

android:layout_height="wrap_content"

android:layout_marginTop="5.0dip" 

android:layout_marginLeft="5.0dip"

android:layout_marginRight="5.0dip" 

android:layout_weight="1.0"

android:text="post注册" />


</LinearLayout>


<TextView 

   android:layout_width="fill_parent"

android:layout_height="wrap_content" 

android:text="服务器返回数据:"

android:layout_marginTop="5.0dip" 

android:layout_marginLeft="5.0dip"

android:layout_marginRight="5.0dip" 

android:textStyle="bold"

android:textAppearance="?android:textAppearanceMedium" />

<TextView android:id="@+id/response_msg" 

   android:layout_width="fill_parent"

android:layout_height="150dip" 

android:layout_marginTop="5.0dip"

android:layout_marginLeft="5.0dip" 

android:layout_marginRight="5.0dip"

android:textStyle="bold" 

android:textAppearance="?android:textAppearanceMedium" />


</LinearLayout>




2.MainActivity.java代码:


public class MainActivity extends Activity {


private static final String SERVER_ADDRESS = "http://10.248.27.195:8080/HttpServer/UserRegisterServer";


private EditText username;

private EditText password;

private Button getMetond;

private Button postMethod;

private TextView responseMessage;

Handler handler=new Handler(){

public void handleMessage(android.os.Message msg) {

if(msg.what==0x101){

Bundle bundle=msg.getData();

   String responseMsg = bundle.getString("msg");

   responseMessage.setText(responseMsg);

       }

}

};

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);


// 初始化控件

username = (EditText) findViewById(R.id.username);

password = (EditText) findViewById(R.id.password);

getMetond = (Button) findViewById(R.id.button_get);

postMethod = (Button) findViewById(R.id.button_post);

responseMessage = (TextView) findViewById(R.id.response_msg);

responseMessage.setBackgroundColor(Color.BLACK);

responseMessage.setTextColor(Color.WHITE);

getMetond.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

registerByGetRequest();

}

});

// 注册"以GET方式注册"按钮事件监听器,以GET方式发送数据,并显示服务器返回结果

postMethod.setOnClickListener(new OnClickListener() {

public void onClick(View v) {


registerByPostRequest();

}

});

}

  // 注册"以POST方式注册"按钮事件监听器, 以POST方式发送数据,并显示服务器返回结果


/**

* 以GET请求方式与服务器进行通信

*/

private void registerByGetRequest() {

new Thread(new Runnable() {

public void run() {

// TODO Auto-generated method stub

Message m=new Message();

m.what=0x101;

Bundle bundle=new Bundle();

try {

String url = new StringBuffer(SERVER_ADDRESS).append("?un=")

.append(username.getText().toString().trim())

.append("&pwd=")

.append(password.getText().toString().trim())

.toString();

HttpClient httpClient = new DefaultHttpClient();

httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);

               httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000    );

               //超时操作

HttpGet httpGetRequest = new HttpGet(url);

HttpResponse response = httpClient.execute(httpGetRequest);

if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode())

{

String responseMsg = "Get方式注册信息\n"+EntityUtils.toString(response.getEntity());

bundle.putString("msg",responseMsg);

m.setData(bundle);

handler.sendMessage(m);

}else{

String errorMsg = "错误";

bundle.putString("msg",errorMsg);

m.setData(bundle);

handler.sendMessage(m);

}

}catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

bundle.putString("msg","链接服务器超时");

               m.setData(bundle);

               handler.sendMessage(m);

e.printStackTrace();

}

}

}).start();

}


/**

* 以POST请求方式与服务器进行通信

*/

private void registerByPostRequest() {


        new Thread(new Runnable() {

public void run() {

// TODO Auto-generated method stub

Message m=new Message();

m.what=0x101;

Bundle bundle=new Bundle();

try {

HttpClient httpClient = new DefaultHttpClient();

//初始化HttpClient对象

HttpPost httpPostRequest = new HttpPost(SERVER_ADDRESS);

//创建HttpPost链接

httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);

               httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000    );

               //超时操作

List<NameValuePair> paramList = new ArrayList<NameValuePair>();

BasicNameValuePair userNameParam = new BasicNameValuePair("un", username.getText().toString().trim());

BasicNameValuePair emailParam = new BasicNameValuePair("pwd", password.getText().toString().trim());

paramList.add(userNameParam);

paramList.add(emailParam);

//数据处理


HttpEntity httpEntity = new UrlEncodedFormEntity(paramList, HTTP.UTF_8);

//对数据进行编码

httpPostRequest.setHeader("content-type", "text/html");

//设置数据类型

httpPostRequest.setEntity(httpEntity);

//向服务器发送HttpPost请求

HttpResponse response = httpClient.execute(httpPostRequest);

//读取服务器返回的数据

if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()){

String responseMsg = "Post注册信息\n"+EntityUtils.toString(response.getEntity());

bundle.putString("msg",responseMsg);

m.setData(bundle);

handler.sendMessage(m);

}else{

String errorMsg = "错误:" + response.getStatusLine().toString();

bundle.putString("msg",errorMsg);

m.setData(bundle);

handler.sendMessage(m);

}

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

               bundle.putString("msg","链接服务器超时");

               m.setData(bundle);

               handler.sendMessage(m);

e.printStackTrace();

}

}

}).start();

}

}




服务器端:


UserRegisterServer.java代码:


public class UserRegisterServer extends HttpServlet {

private static final long serialVersionUID = 1L;

       

    /**

     * @see HttpServlet#HttpServlet()

     */

    public UserRegisterServer() {

        super();

    }


/**

* 当请求为HTTP GET时执行此方法

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String userName = request.getParameter("un");

String password = request.getParameter("pwd");

if(userName!=""&&password!=""&&userName!=null&&password!=null){

System.out.println("Get方式用户注册信息:\n");

System.out.println("用户名:" + userName);

System.out.println("邮箱: " + password);

   response.getWriter().print("Register Success!\nID = " + generateUserId());

// 向客户端发送数据

}

else{

System.out.println("用户名或邮箱不正确");

response.getWriter().print("UserName ERROR or Email ERROR!");

}

}


/**

* 当请求为HTTP POST时执行此方法

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// 读取从客户端发送来的数据

BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));

        String data = null;

        StringBuilder sb = new StringBuilder();

        while((data = br.readLine())!=null){

            sb.append(data);

        }

    

        String temp = URLDecoder.decode(sb.toString(), "utf-8");

        // 对数据进行解码操作

        System.out.println("Post方式用户注册信息:\n " + temp);

        response.getWriter().print("Register Success!\nID = " + generateUserId());

// 向客户端发送数据

}

/**

* 生成随机数代表当前注册用户ID

* @return

*/

private String generateUserId(){

Random ran = new Random();

return String.valueOf(Math.abs(ran.nextInt()));

}

}



这就是完整的代码了,其中get方式和post方式的区别:

1. get是从服务器上获取数据,post是向服务器传送数据。
2. get是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到。post是通过HTTP post机制,将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址。用户看不到这个过程。
3. 对于get方式,用Request.QueryString获取变量的值,对于post方式,用Request.Form获取提交的数据。
4. get传送的数据量较小,不能大于2KB。post传送的数据量较大,一般被默认为不受限制。但理论上,IIS4中最大量为80KB,IIS5中为100KB。
5. get安全性非常低,post安全性较高。但是执行效率却比Post方法好。 

建议:
1、get方式的安全性较Post方式要差些,包含机密信息的话,建议用Post数据提交方式;
2、在做数据查询时,建议用Get方式;而在做数据添加、修改或删除时,建议用Post方式;


使用Apache HttpClient访问网络(实现手机端注册,服务器返回信息)

标签:网络编程   服务器   运行图   客户端   手机   httpclient   

原文地址:http://bigcrab.blog.51cto.com/10626858/1710447

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!