The Android network foreground requests data from the server page

This is a small example of an android front-end requesting a small amount of data from a server-side website.

First design the server, and then write the Android front end.

One: Server

  • Create a new dynamic website, create a new class under the java package to inherit the HttpServlet parent class, rewrite the doGet() method, and output text to the client.
  • Deploy this class, copy the package and class file of this class to the classes directory of WEB-INF, and configure the network path of this file in the web.xml file.

Code for Internet file:

package android;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Internet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO 自动生成的方法存根
		//super.doGet(req, resp);
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter print=resp.getWriter();
		print.println("你好!");//客户端可以接收得到,本网页显示
		print.println("上海!");
		print.flush();//flush()不可以少
		System.out.println("瓜瓜!");//客户端接收不到,本网页不显示,输出在控制台
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO 自动生成的方法存根
		super.doPost(req, resp);
	}

	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		// TODO 自动生成的方法存根
		super.service(arg0, arg1);
	}

	@Override
	public void init() throws ServletException {
		// TODO 自动生成的方法存根
		super.init();
	}

}

configured web.xml

<servlet>
    <servlet-name>a</servlet-name>
    <servlet-class>android.Internet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>a</servlet-name>
    <url-pattern>/b</url-pattern>
  </servlet-mapping>

Access path:

So far the writing on the server side has been successful, and then the writing on the Android side starts.

Two: Android mobile terminal

  • Write the main thread and process the display of the data after the sub-thread gets the data.
  • Write a child thread to connect to the server to get data and send it to the main thread.
  • Attached code:

activity_main.xml has only one control

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" "
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

Main thread MainActivity.java

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
import com.internethttp.R;

public class MainActivity extends ActionBarActivity {
	String url="http://ly-and-tl.uicp.cn:42696/AndroidServer/b";//服务端的servlet页面网址,在web.xml页面中已配置
	TextView tv;
    Handler handler;
    @SuppressLint("HandlerLeak") @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv=(TextView) findViewById(R.id.textView);
        handler=new Handler(){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				if(msg.what==3){//后台发送消息切换回主线程后的处理
					CharSequence ss=(CharSequence)msg.obj;//拿到消息的包裹信息
					System.out.println(ss+"MainActivity");
					if(ss!=null){
					tv.setText(ss);//只能在主线程更新UI
					}
				}
			}
        	
        };
        new HttpThread(url,handler).start();

    }
}

Child thread HttpThread.java

public class HttpThread extends Thread {
	String url;
	Handler handler;
	  HttpThread(String url,Handler hand){
		  this.url=url;
		  handler=hand;
	  }
      @Override
      public void run() {//向后台请求数据
	   // TODO Auto-generated method stub
	   //super.run();
	     URL httpUrl;
	     try {
			httpUrl=new URL(url);
			HttpURLConnection conn=(HttpURLConnection)(httpUrl.openConnection());
//打开服务端的某个页面链接就相当于自动调用doGet()方法
			conn.setReadTimeout(5000);
//5000秒内不返回就报错
			conn.setRequestMethod("GET");
		//bufferReader适合中文类,HttpURLConnection的getInputStream()方法返回一个InputStream对象,
			//InputStreamReader接收InputStream对象能实例化一个InputStreamReader,
			//bufferedReader能接收一个InputStreamReader对象实例化自己
			BufferedReader buff=new BufferedReader(new InputStreamReader(conn.getInputStream()));
			StringBuffer sb=new StringBuffer();
			String str;
			while((str=buff.readLine())!=null){
//readLine()返回String对象,从后台拿到数据存到String对象
				sb.append(str);
			}
			System.out.println(sb+"HttpThread");
			Message msg=handler.obtainMessage(3);
			msg.obj=sb;
			handler.sendMessage(msg);
//发送到主线程,立刻切换线程
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
      }
}

Finally, don't forget to set the network permissions.

running result:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325061845&siteId=291194637