Webt通信的Get、Post方法

首先我们要了解Tomcat,Tomcat 服务器是一个免费的开放源代码的Web 应用服务器,属于轻量级应用服务器,在中小型系统和并发访问用户不是很多的场合下被普遍使用,是开发和调试JSP 程序的首选。当配置正确时,Apache 为HTML页面服务,而Tomcat 实际上运行JSP 页面和Servlet。另外,Tomcat和IIS等Web服务器一样,具有处理HTML页面的功能,另外它还是一个Servlet和JSP容器,独立的Servlet容器是Tomcat的默认模式。

意思就是说,下载Tomcat解压后,打开bin目录下的startup.bat,当运行出Server startup in ****ms后,就相当于运行了一个小型服务器,此时,我们就可以通过Activity进行Web通信。想实现Get、Post方法,还必须了解你下载的Webapps中的内容,具体在代码中会展现。

Get、Post在子线程中处理,因为如果在主线程中运行的话,AdroidStudio的一个特点是主线程中如果运行时间过长,运行时会结束运行,此时Get,Post这些费时间的操作要移到子线程中处理,这样可优化程序运行。

还需要注意一点的是,当调试程序是,手机和PC机要处于同一网段,即两者要连在同一个网内,局域网也好,外网也好。建议在PC上开放一个WIFI,手机连上WIFI,至于获得PC机的IP,快捷键Window+R键,输入cmd,在弹出的对话框内输入ipgonfit,可获得PC的IP。值得一说的是,Get,Post等方法基本都是固定程序,我上传了我用的Tomcat,希望有帮助。

importandroid.os.AsyncTask;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.administrator.intent.R;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class WebActivity extends AppCompatActivity {
    private TextView tv;                                 //用于展现Get、Post方法的结果
    private Button search,search1;                      //search表示Get方法,search1表示Post方法

@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web); search= (Button) findViewById(R.id.search); tv= (TextView) findViewById(R.id.tv); search1= (Button) findViewById(R.id.search1); search.setOnClickListener(new View.OnClickListener() { //172.23.72.1:8080表示PC机的IP地址

            @Override
            public void onClick(View v) {
                String url="http://172.23.72.1:8080/HttpTest/index.jsp?option=getUser&uName=jerehedu";
                new MygetJob().execute(url);                    //MygetJob为自己编写的方法
            } 
        });
        search1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("===","xxxxxxxx");                        //Log等方法可用于判断程序是否运行此处
                                                                  //也可以用Debug模式来判断
                String[] arg=new String[2];
                arg[0]="http://172.23.72.1:8080/HttpTest/index.jsp?option=getUser&uName=jerehedu";
                arg[1]="option=getUser&uName=jerehedu";
                  new MyPostJob().execute(arg);
            }
        });
    }




public class MyPostJob extends AsyncTask<String,Void,String>{
    @Override
    protected String doInBackground(String... strings) {
        HttpURLConnection con = null;
        InputStream is = null;
        StringBuilder sbd = new StringBuilder();
        try {
            URL url = new URL(strings[0]);
            con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(5*1000);                    
            con.setReadTimeout(5*1000);        
            con.setRequestMethod("POST");      
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Charset","UTF-8");
            con.setRequestProperty("Content-type","application/x-www-form-urlencoded");
            //params应该是这样的样式 => option=getUser&uName=jerehedu
            String params = strings[1];
            OutputStream os = con.getOutputStream();
            os.write(params.getBytes());
            os.flush();
            os.close();
            if(con.getResponseCode()==200){
                is = con.getInputStream();
                int next = 0 ;
                byte[] b = new byte[1024];
                while ((next = is.read(b))>0){
                    sbd.append(new String(b,0,next));
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(con!=null){
                con.disconnect();
            }
        }
        return sbd.toString();
    }
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        tv.setText("POST请求结果:"+s);
    }
}

    /**AsyncTask异步任务类
      异步任务类的参数
     第一个参数会传到doInbackgrond方法中
     第三个参数指定doInbackgrond的返回值
                   doInbackgrond的返回值会被onPostExecute接收
     */
    public class MygetJob extends AsyncTask<String,Void,String>{

        //onPreExecute在主线程中执行命令,通常进度条的初始化
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        //doInBackground在子线程中执行命令
        @Override
        protected String doInBackground(String... params) {
            HttpURLConnection con=null;
            InputStream is = null;
            StringBuilder sbd=new StringBuilder();
            try {
                URL url=new URL(params[0]);
                con  = (HttpURLConnection)url.openConnection();
                con.setConnectTimeout(5*1000);
                con.setReadTimeout(5*1000);
                /* Http响应码
                  200 成功
                  404 未找到
                  500 发生错误
                 */
                if(con.getResponseCode()==200){
                  is =  con.getInputStream();
                    int next=0;
                    byte[] bt = new byte[1024];
                    while ((next=is.read(bt))>0){
                        sbd.append(new String(bt,0,next));
                    }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
               if(is!= null){
                   try {
                       is.close();
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
               }
                if(con!=null){
                    con.disconnect();
                }
            }
              return sbd.toString();
        }

        //onPostExecute在UI线程中执行
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            tv.setText(s);
        }
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值