Android HTTP Communication

Source: Internet
Author: User

1. Server-side
The simplest server-side receive code that directly prints the data across both *

 PackageCn.servlet;ImportJava.io.IOException;ImportJavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/** * Servlet Implementation class Myservlet */@WebServlet("/myservlet") Public  class myservlet extends httpservlet {    Private Static Final LongSerialversionuid =1L/** * @see httpservlet#httpservlet () */     Public Myservlet() {Super();//TODO auto-generated constructor stub}/** * @see httpservlet#doget (httpservletrequest request, httpservletresponse response) */    protected void Doget(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {//TODO auto-generated method stub        //Insist on calling the Post method         This. DoPost (Request, response); }/** * @see httpservlet#dopost (httpservletrequest request, httpservletresponse response) */    protected void DoPost(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {//TODO auto-generated method stub        //Data acquisitionString name = Request.getparameter ("Name"); String age = Request.getparameter ("Age");//Print dataSYSTEM.OUT.PRINTLN (name);    System.out.println (age); }}

Sevlet


Myservlet
Cn.servlet.MyServlet


Myservlet
/ss

2. Client
First we customize a thread

publicclass Thread1 extends Thread//数据来自布局的文本编辑框String name ;    String age;    String url;    publicThread1(String name, String age,String url){        this.name=name;        this.age=age;        this.url=url;    }

1) Implementation of the Get method

 Public voidDoget () {Try{places of special attention of the//get methodurl=url+"? name="+urlencoder.encode (Name,"Utf-8")+"&age="+age;//Convert to URL objectURL Httpurl =NewURL (URL);//Get Connection objectHttpURLConnection conn = (httpurlconnection) httpurl.openconnection ();//Set Transfer methodConn.setrequestmethod ("GET"); Conn.setreadtimeout ( the);//Read input streamBufferedReader br =NewBufferedReader (NewInputStreamReader (Conn.getinputstream ())); StringStr; StringBuffer SB =NewStringBuffer ();//Put SB in separate                 while((Str=br.readline ())! =NULL) {Sb.append (Str); }        }Catch(Malformedurlexception e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }    }

2) The implementation of the Post method

 Public void DoPost(){Try{URL Httpurl =NewURL (URL);            HttpURLConnection conn = (httpurlconnection) httpurl.openconnection (); Conn.setrequestmethod ("POST"); Conn.setreadtimeout ( the);//Note This is Conn.getoutputstream, not new, so it can be linked .OutputStream out=conn.getoutputstream (); String content ="Name="+name+"&age="+age; out. Write (Content.getbytes ()); BufferedReader br =NewBufferedReader (NewInputStreamReader (Conn.getinputstream ()));            String str; StringBuffer SB =NewStringBuffer (); while((Str=br.readline ())! =NULL) {sb.append (str); }        }Catch(Malformedurlexception e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }    }

Which method is executed in the Run method is used in the appropriate way

@Override    publicvoidrun() {        // TODO Auto-generated method stub        super.run();    doGet();//      doPost();    }

3) The layout of the client input data is simple, two edit text boxes and a button

private EditText etName,etAge;    private Button btnReg;

4) button click event

 btnReg.setOnClickListener(new OnClickListener() {            publicvoidonClick(View arg0) {                // TODO Auto-generated method stub                //把ip地址改为自己目前的                "http://192.168.191.1:8080/serve/ss";                new Thread1(etName.getText().toString(), etAge.getText().toString(), url).start();            }        });    }

Android HTTP Communication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.