android http 通信

最近简单看了,android http的通信,写了一个小例子,记录一下

首先搭配好android环境,直接从官网下Android Developer Tools 基本都搭配好了,然后本机启动一个web服务器

servlet

@SuppressWarnings("serial")
@WebServlet(value = "/as1")
public class ServletTest extends HttpServlet {
 public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 private static final Logger log4jLogger = Logger.getLogger(ServletTest.class);
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
  String clientIp = req.getRemoteAddr();
  String param1 = req.getParameter("p1");
  String param2 = req.getParameter("p2");
  String rtn = "";
  try {
   rtn = "当前的服务器时间是: " + DATE_FORMAT.format(new Date())+"\r\n";
   rtn +="传来的参数1:"+param1+"\r\n";
   rtn +="传来的参数2:"+param2+"\r\n";
    ServletOutputStream sout = resp.getOutputStream();
    sout.write(rtn.getBytes("UTF-8"));
    sout.flush();
    sout.close();
  } catch (Exception e) {
   log4jLogger.error("clilent "+clientIp +" request current server time error");
   e.printStackTrace();
  }
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doGet(req, resp);
 }
 
}

 启web动服务器

android application

启动模拟器 模拟器访问本机的地址默认是10.0.2.2

public class MainActivity extends Activity {

 
 private TextView disServerTime ;
 private StringBuffer result = new StringBuffer();
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  initStrictMode();
  setContentView(R.layout.activity_main);
  disServerTime = (TextView) findViewById(R.id.displayServerTime);
  findViewById(R.id.btn_getServerTime).setOnClickListener(
    new View.OnClickListener() {
     @Override
     public void onClick(View view) {
      try {
       getServerTime_http_post();
      } catch (Exception e) {
       e.printStackTrace();
       result.append("出现异常:"+e.getMessage()+"\n");
       result.append(e.getClass().getName()+"\n");
      }
      disServerTime.setText(result.toString());
     }
    });
  findViewById(R.id.btn_getServerTime1).setOnClickListener(
    new View.OnClickListener() {
     @Override
     public void onClick(View view) {
      try {
       getServerTime_http_get();
      } catch (Exception e) {
       result.append("出现异常:"+e.getMessage()+"\n");
       result.append(e.getClass().getName()+"\n");
      }
      disServerTime.setText(result.toString());
     }
    });
  findViewById(R.id.btn_getServerTime2).setOnClickListener(
    new View.OnClickListener() {
     @Override
     public void onClick(View view) {
      try {
       getServerTime_url_post();
      } catch (Exception e) {
       result.append("出现异常:"+e.getMessage()+"\n");
       result.append(e.getClass().getName()+"\n");
      }
      disServerTime.setText(result.toString());
     }
    });
  findViewById(R.id.btn_getServerTime3).setOnClickListener(
    new View.OnClickListener() {
     @Override
     public void onClick(View view) {
      try {
       getServerTime_url_get();
      } catch (Exception e) {
       result.append("出现异常:"+e.getMessage()+"\n");
       result.append(e.getClass().getName()+"\n");
      }
      disServerTime.setText(result.toString());
     }
    });
 }

 private void getServerTime_http_post() throws Exception {
  
  result.delete(0, result.length());
  // http地址
  String httpUrl = "http://10.0.2.2:8080/servlet-async/as1";
  //HttpGet连接对象         
  HttpPost httpRequest = new HttpPost(httpUrl);
  //取得HttpClient对象             
  HttpClient httpclient = new DefaultHttpClient();
  
   List<NameValuePair> params = new ArrayList <NameValuePair>();  
         params.add(new BasicNameValuePair("p1", "getServerTime_httpclient_post_test"));  
         params.add(new BasicNameValuePair("p2", "中文参数测试"));  
  httpRequest.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
  
  //请求HttpClient,取得HttpResponse
  HttpResponse httpResponse = httpclient.execute(httpRequest);
  //请求成功           
  if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
   result.append("请求成功 ,连接返回状态:"+httpResponse.getStatusLine().getStatusCode()+"\n");
   String strResult = EntityUtils.toString(httpResponse.getEntity(),"utf-8");
   result.append(strResult+"\n");
             
  } else {
   result.append("请求错误,连接返回状态:"+httpResponse.getStatusLine().getStatusCode()+"\n");
  }
 }
 private void getServerTime_http_get() throws Exception {
  
  result.delete(0, result.length());
  // http地址
  String httpUrl = "http://10.0.2.2:8080/servlet-async/as1";
  //HttpGet连接对象         
  HttpGet httpRequest = new HttpGet(httpUrl+"?p1=getServerTime_http_get&p2="+URLEncoder.encode("中文参数测试","utf-8"));
  //取得HttpClient对象             
  HttpClient httpclient = new DefaultHttpClient();
  
  //请求HttpClient,取得HttpResponse
  HttpResponse httpResponse = httpclient.execute(httpRequest);
  //请求成功           
  if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
   result.append("请求成功 ,连接返回状态:"+httpResponse.getStatusLine().getStatusCode()+"\n");
   String strResult = EntityUtils.toString(httpResponse.getEntity(),"utf_8");
   result.append(strResult+"\n");
              
  } else {
   result.append("请求错误,连接返回状态:"+httpResponse.getStatusLine().getStatusCode()+"\n");
  }
 }
 private void getServerTime_url_post() throws Exception {
  result.delete(0, result.length());
  URL url = new URL("http://10.0.2.2:8080/servlet-async/as1");
  HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
  urlConn.setDoInput(true);
  urlConn.setDoOutput(true);
  urlConn.setUseCaches(false);
  urlConn.setRequestMethod("POST");
  urlConn.setRequestProperty("Charset", "utf-8");
  
  
  DataOutputStream out = new DataOutputStream(urlConn.getOutputStream()); 
  String content = "p1=getServerTime_url_post&p2=" + URLEncoder.encode("中文参数测试","utf-8");
  out.writeBytes(content);

  out.flush();
  out.close();  
  
  InputStreamReader in = new InputStreamReader(urlConn.getInputStream(),"UTF-8");

  BufferedReader buffer = new BufferedReader(in);
  String inputLine = null;
           
  while (((inputLine = buffer.readLine()) != null)) {
     result.append(inputLine + "\n"); 
  }

 in.close();                  
        
  
  urlConn.disconnect();
  
 }
 private void getServerTime_url_get() throws Exception {
  result.delete(0, result.length());
  URL url = new URL("http://10.0.2.2:8080/servlet-async/as1?p1=getServerTime_url_get&p2=" + URLEncoder.encode("中文参数测试","utf-8"));
  HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
  urlConn.setDoInput(true);
  urlConn.setUseCaches(false);
  urlConn.setRequestMethod("GET");
  InputStreamReader in = new InputStreamReader(urlConn.getInputStream(),"UTF-8");
 
  BufferedReader buffer = new BufferedReader(in);
  String inputLine = null;
  String resultData = "";
              
  while (((inputLine = buffer.readLine()) != null)) {
   result.append(inputLine + "\n"); 
  }

  in.close();                  

  urlConn.disconnect();
  
 }
 @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;
 }

 @SuppressLint("NewApi")
 private void initStrictMode() {
  // 判断操作系统是Android版本3.0以上版本
  if (android.os.Build.VERSION.SDK_INT >= 11) {
   StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads()
     .detectDiskWrites().detectNetwork().penaltyLog().build());
   StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() 
              .detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath().build());
  }
 }
}

最后结果

 

 

需要注意的用get方法传参数时需要根据你自己的环境配置编码

可用utf-8,然后服务器端过滤所有的get请求具体可百度一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值