Android客户端与Web服务器端Http通信

首先需要在Web服务器端配置struts2的jar包以及json包(可以参考使用谷歌的gson)所依赖的jar包并导入到web项目中。


下面是Web服务器端的配置代码:

在web.xml文件中配置struts2并交给action去处理,以下是web.xml配置代码

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>PatientInfo</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<filter>
		<filter-name>StrutsPrepareAndExecuteFilter</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>StrutsPrepareAndExecuteFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>


接下来创建struts.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
	
	<package name="Demo" namespace="/" extends="struts-default" >
		<action name="login" class="org.com.action.LoginAction">
			<result name="success">/index.jsp</result>
		</action>
	</package>
    <constant name="struts.enable.SlashesInActionNames" value="true"/>
     
</struts>


并创建LoginAction.java文件,实现struts配置文件中写的login方法

package org.com.action;


import java.sql.Connection;


import javax.servlet.http.HttpServletRequest;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;


import com.opensymphony.xwork2.ActionSupport;


public class LoginAction extends ActionSupport implements ServletRequestAware{


<span style="white-space:pre">	</span>private HttpServletRequest request;
<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span>public void login() throws Exception {
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>JSONObject json=new JSONObject();
<span style="white-space:pre">		</span>json.put("username","username");
<span style="white-space:pre">		</span>json.put("password","password");
<span style="white-space:pre">		</span>response.setContentType("text/html;charset=utf-8");
<span style="white-space:pre">		</span>PrintWriter out=response.getWriter();
<span style="white-space:pre">		</span>out.println(json.toString());
<span style="white-space:pre">		</span>out.flush();
<span style="white-space:pre">		</span>out.close();
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>@Override
<span style="white-space:pre">	</span>public void setServletRequest(HttpServletRequest request) {
<span style="white-space:pre">		</span>// TODO Auto-generated method stub
<span style="white-space:pre">		</span>this.request=request;
<span style="white-space:pre">	</span>}
}

接下来就是配置android客户端。

首先需要在AndroidManifest.xml里边加入网络权限:

<uses-permission android:name="android.permission.INTERNET" />


最后就是客户端代码

package com.maylor.demo;  
  
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.ClientProtocolException;  
import org.apache.http.client.HttpClient;  
import org.apache.http.client.methods.HttpGet;  
import org.apache.http.impl.client.DefaultHttpClient;  
import org.json.JSONArray;  
import org.json.JSONException;  
import org.json.JSONObject;  
  
import android.annotation.SuppressLint;  
import android.app.Activity;  
import android.os.Bundle;
import android.os.Message;  
import android.util.Log;  
import android.view.Menu;  
import android.widget.TextView;  
  
public class MainActivity extends Activity {  
    private static String URL = "http://192.168.1.2:8080/Demo/login";
    private TextView mTextView;
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main); 
        ProgressDataAsyncTask asyncTask = new ProgressDataAsyncTask();
		asyncTask.execute(1000);
    }  
  
    /** 
     * 请求web服务器数据 
     *  
     * @param url 
     */  
    private String getServerData() {  
        new Thread() {  
            public void run() {  
                DefaultHttpClient client = new DefaultHttpClient();  
                HttpPost request;  
                String msg = "";  
                try {  
                    request = new HttpPost(URL);  
                    HttpResponse response = client.execute(request);  
                    // 判断请求是否成功  
                    if (response.getStatusLine().getStatusCode() == 200) {  
                        String strResult = EntityUtils.toString(response.getEntity()); 
                        return strResult;
                    }else{
                    return null;
                    }
                } catch (ClientProtocolException e) {  
                    e.printStackTrace();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }.start();  
    }

    private class ProgressDataAsyncTask extends AsyncTask<Integer, Integer, String> {

		public ProgressDataAsyncTask() {
			super();
		}

		@Override
		protected String doInBackground(Integer... params) {
			ArrayList<BasicNameValuePair> urlParams = new ArrayList<BasicNameValuePair>();
			try {
				return getServerData();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		protected void onPostExecute(String result) {
			mTextView.setText(result);
		}

	}  
  
    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        // Inflate the menu; this adds items to the action bar if it is present.  
        getMenuInflater().inflate(R.menu.main, menu);  
        return true;  
    }  
} 

到这里,Android客户端与Web服务器端之间简单的通信就已经完成了。







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值