[2015/05/08] 最简单的服务器 - 安卓通信

仅作记录用,毫无技术含量。

我得记得把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() {			
			@Override
			public 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");
					//请求HttpRequest
					hPost.setEntity(httpEntity);
					//取得默认的HttpClient
					HttpClient httpClient=new DefaultHttpClient();
					//声明HttpResponse
					HttpResponse httpResponse;
					//获取HttpResponse
					httpResponse=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 stub
		buttonget=(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] 我去上微机课了先酱!好多需要完善的!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值