[2015/05/08] 最简单的服务器 - 安卓通信
来源:互联网 发布:找一个程序员女朋友 编辑:程序博客网 时间:2024/05/22 13:14
仅作记录用,毫无技术含量。
我得记得把json相关的资料给转载一下,等上完微机课= =
/***************更新日志***************/
2015/05/08 创建,仅从jsp页面读取。
/***************************************/
服务器端程序(连的CMCC-EDU, 服务器访问地址 http://10.50.21.213:8080/HttpConnect/)
Login.jsp(这格式我也是醉,但没时间改了)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Hi, Android</title></head><body color="cyan">This is a jsp file to connect to Android App.<hr><form action="Result.jsp" method="post"><table><tr><td>用户名:</td><td><input type="text" name="username" value=""></td></tr><tr><td>密码:</td><td><input type="password" name="password" value=""></td></tr></table><br><input type="submit" name="submit" value="提交"></form></body></html>
Result.jsp(注释还没写完,但是没时间了……)
<%@page import="com.google.gson.Gson"%><%@page import="java.util.HashMap"%><%@page import="java.util.Map"%><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% //在lib中导入了一个json生成的jar包Gson Gson gson = new Gson(); Map<String, Object> mapt = new HashMap<String, Object>(); //获取username和password(这个参数是从安卓传过去的) String username = request.getParameter("username"); String password = request.getParameter("password"); mapt.put("username", username); mapt.put("password", password); Map<String,Object>map=new HashMap<String,Object>(); map.put("user",mapt); String result = gson.toJson(map); System.out.println(result); out.append(result); %>
安卓端程序
布局文件 activity_main.xml
<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.sutdy.MainActivity" ><ScrollView android:layout_width="300dp" android:layout_height="1000dp" android:layout_toLeftOf="@+id/post" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="280dp" android:layout_height="wrap_content" android:id="@+id/text" android:text="@string/test"/> </LinearLayout> </ScrollView> <Button android:id="@+id/get" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginTop="14dp" android:text="GET" /> <Button android:id="@+id/post" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/get" android:layout_below="@+id/get" android:layout_marginTop="15dp" android:text="POST" /></RelativeLayout>
MainActivity.java(是的,我发现我的包名………………………………我没资格嘲笑人家!)
package com.sutdy;import java.io.IOException;import java.io.PrintWriter;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import android.app.Activity;import android.os.Bundle;import android.os.StrictMode;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity {private Button buttonget,buttonpost;private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initWidgets(); initStrictMode(); buttonget.setOnClickListener(new OnClickListener() {public void onClick(View v) {try{ //通过该IP地址实例化HttpGet对象 HttpGet httpGet=new HttpGet("http://www.baidu.com"); //实现HttpClient接口 HttpClient httpClient=new DefaultHttpClient(); //声明一个HttpResponse对象 HttpResponse hResponse; //执行Get请求 hResponse=httpClient.execute(httpGet); if(hResponse.getStatusLine().getStatusCode()==200){ //连接成功 //得到HttpEntity对象并将其转换为String类 String strResult=EntityUtils.toString(hResponse.getEntity()); //显示HttpEntity textView.setText(strResult); } }catch(ClientProtocolException e){ e.printStackTrace(); }catch (IOException e) { e.printStackTrace();} }}); buttonpost.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {//HttpPost连接对象HttpPost hPost=new HttpPost("http://10.50.21.213:8080/HttpConnect/Result.jsp");//使用NameValuePair保存要传递的POST参数List<NameValuePair> params=new ArrayList<NameValuePair>();//添加要传递的POST参数params.add(new BasicNameValuePair("username", "zhizhi"));params.add(new BasicNameValuePair("password", "zhizhi19950801"));try{//设置字符集HttpEntity httpEntity=new UrlEncodedFormEntity(params,"utf-8");//请求HttpRequesthPost.setEntity(httpEntity);//取得默认的HttpClientHttpClient httpClient=new DefaultHttpClient();//声明HttpResponseHttpResponse httpResponse;//获取HttpResponsehttpResponse=httpClient.execute(hPost);//连接成功if (httpResponse.getStatusLine().getStatusCode()==200){//获取返回的信息String resultString=EntityUtils.toString(httpResponse.getEntity());//str返回的是一个标准的json格式String str=new String(resultString.getBytes("utf-8"),"utf-8");//由于这次的str是单个数据的json,所以调用parseJson否则调用parseJsonMulti//方法自带输出parseJson(str);//显示返回的信息//textView.setText(str);}}catch(Exception e){e.printStackTrace();}}}); }/** * 设置线程政策,防止抛出异常 */ private void initStrictMode() { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskReads() .detectNetwork() .build()); //设置虚拟内存政策 StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build()); } /** * 初始化控件,并获取相应id */private void initWidgets() {// TODO Auto-generated method stubbuttonget=(Button)findViewById(R.id.get);buttonpost=(Button)findViewById(R.id.post);textView=(TextView)findViewById(R.id.text);}/** * 解析单个Json格式 * @param strResult */private void parseJson(String strResult) { try { //JSON对象格式构造器,从strResult中获得主键"user" JSONObject jsonObj = new JSONObject(strResult).getJSONObject("user"); //获取user的username String username = jsonObj.getString("username"); //获取user的password String password = jsonObj.getString("password"); //设置文本格式 textView.setText("用户名:"+username + ",密码:" + password); } catch (JSONException e) { System.out.println("Json parse error"); e.printStackTrace(); } }/** * 解析多个数据的Json(即有数组格式) * @param strResult */ private void parseJsonMulti(String strResult) { try { //JSON数组格式构造器,从strResult中获得主键"user" JSONArray jsonObjs = new JSONObject(strResult).getJSONArray("user"); //初始化最终显示结果s String s = ""; //循环,将数组的值放入s中 for(int i = 0; i < jsonObjs.length() ; i++){ JSONObject jsonObj = ((JSONObject)jsonObjs.opt(i)) .getJSONObject("user"); String username = jsonObj.getString("username"); String password = jsonObj.getString("password"); s += "用户名:" + username + ",密码:" + password ; } textView.setText(s); } catch (JSONException e) { System.out.println("Jsons parse error !"); e.printStackTrace(); } } }
运行结果如下:
[2015/05/08] 我去上微机课了先酱!好多需要完善的!
0 0
- [2015/05/08] 最简单的服务器 - 安卓通信
- 最简单的安卓环境搭建
- [2015/05/08] JSP服务器与安卓客户端通信 & 页面布局控件覆盖问题
- 最简单最时尚的安卓时间选择器
- 安卓开发中服务器与客户端的通信
- 安卓实现gtalk的xmpp简单通信
- 安卓客户端与服务器端的简单通信
- 安卓APP客户端与服务器通信
- 安卓开发环境最简单的搭建方法
- 最简单的安卓智能灯控制系统外观设计
- 安卓开发最简单的按键监听事件
- 安卓开发最简单的网络广播监听
- 最简单的web服务器
- 最简单的时间服务器
- 简单的安卓程序和web服务器
- 基于TCP的最简单的通信
- 最简单安卓sqlite数据库
- 一个最简单的Socket通信例子
- android Activity之间递 bundle对象传递
- HIVE使用小计
- 《剑指Offer》学习笔记--面试题16:反转链表
- oracle安装过程中 遇到错误正在检查操作系统要求...要求的结果: 5.0,5.1,5.2,6.0 之一
- vs2010 问题 >LINK : fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
- [2015/05/08] 最简单的服务器 - 安卓通信
- spring,mybatis事务管理配置与@Transactional注解使用
- [POJ] 1579 -> Function Run Fun
- 在notepad++中直接运行python脚本
- Ubuntu上利用Chef实现磁盘的自动分区、自动挂载
- 基于STM32的无线飞鼠(一)
- Python多线程抓取代理服务器
- jeecg权限管理介绍表单级别数据权限
- UVA 11054 Wine trading in Gergovia (酒的交易问题)