Android:网络存储(2)

访问web,web发布到服务器,通过访问服务器来访问程序
安卓访问:
1.servlet必须发布到服务器
2.服务器是开启的状态 通过访问服务器上servlet地址来访问dopost
3.在安卓端使用异步来访问servlet
类继承AsyncTask

安卓访问web,并从中取值

1.布置页面

在这里插入图片描述
代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.black.sq.lesson13.Main3Activity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登陆"
        android:id="@+id/button2"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="155dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="用户名:"
        android:textSize="25dp"
        android:id="@+id/un"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="40dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="密码:"
        android:textSize="25dp"
        android:id="@+id/pw"
        android:layout_below="@+id/un"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="68dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_alignTop="@+id/un"
        android:layout_toRightOf="@+id/un"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText2"
        android:layout_alignTop="@+id/pw"
        android:layout_toRightOf="@+id/pw"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>

2.web servlet 代码

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;

/**
 * Servlet implementation class MyServlet2
 */
public class MyServlet2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyServlet2() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//System.out.print(123);
		String un=request.getParameter("un");
		String pw=request.getParameter("pw");
		System.out.println(un+"-"+pw);
		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-Type", "text/html; charset=utf-8");
		PrintWriter out=response.getWriter();
		if("admin".equals(un)&&"123".equals(pw)){
			out.print("成功");
		}else{
			out.print("失败");
		}				
		out.flush();
		out.close();
	}
}

MainActivity代码

public class Main3Activity extends AppCompatActivity {
    private Button button;
    private EditText un;
    private EditText pw;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        button= (Button) findViewById(R.id.button2);

        un= (EditText) findViewById(R.id.editText);
        pw= (EditText) findViewById(R.id.editText2);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //异步访问selvet
                String unV=un.getText().toString().trim();
                String pwV=pw.getText().toString().trim();
                String info= null;
                try {
                    info = new MyTask1(unV,pwV).execute("http://10.151.2.14:8080/lesson13/MyServlet2").get();
                    Log.i("message",info);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }

            }
        });
    }
}
class MyTask1 extends AsyncTask<String,Void,String>{
    String unV,pwV;
    MyTask1(String unV,String pwV){
        this.unV=unV;
        this.pwV=pwV;
    }
    @Override
    protected String doInBackground(String... params) {

        try {
            params[0]=params[0]+"?un="+unV+"&pw="+pwV;
            HttpURLConnection httpURLConnection= (HttpURLConnection) new URL(params[0]).openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setReadTimeout(8000);

            BufferedReader bufferedReader= new BufferedReader(new InputStreamReader( httpURLConnection.getInputStream()));
            String info=   bufferedReader.readLine();
          //  Log.i("message",info);
            return info;
        } catch (java.io.IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
    }
}

以上是get方式传值

post方式传值

    httpURLConnection.setRequestMethod("POST");
    String param="un="+unV+"&pw="+pwV;
    OutputStream outputStream= httpURLConnection.getOutputStream();
    outputStream.write(param.getBytes());
    outputStream.close();

安卓访问web,从中取图片

1.在eclipse中添加一张图片

在这里插入图片描述

2.布局

在这里插入图片描述

3.MainActivity 代码

public class Main4Activity extends AppCompatActivity {

    private ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main4);
        imageView= (ImageView) findViewById(R.id.imageView2);

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new MyTask2().execute("http://10.151.2.14:8080/lesson13/image/out.jpg");
            }
        });
    }
    class MyTask2 extends AsyncTask<String,Void,Bitmap>{

        @Override
        protected Bitmap doInBackground(String... params) {

            try {
                HttpURLConnection httpURLConnection= (HttpURLConnection) new URL(params[0]).openConnection();
                //post方式传值
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setReadTimeout(8000);

                Bitmap bitmap= BitmapFactory.decodeStream(httpURLConnection.getInputStream());

                return bitmap;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            imageView.setImageBitmap(bitmap);
        }
    }
}
发布了146 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43689040/article/details/103846737