android端与服务器端的通信交互

之前有人说复制了我编写的类,运行不成功,晕,再次编辑下。

有几点要注意的地方:

1、要在androidMainfest.xml中增加权限

<!-- 使用网络功能所需权限 -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.INTERNET" >
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
    </uses-permission>

2、在android3.0前,在UI线程中时可以使用网络传输的,但是,我们都知道,网络传输有延迟,而一旦网络信号不好,我们进行网络传输,就会卡住,android自带的防护机制,当程序卡住超过5秒后,就会自动蹦出个提示框,说XX程序无响应,是否将其关闭。所以,现在的进行网络传输,都要新建一个线程,在线程中操作。

但是,如果我们非要在UI线程下使用网络操作的话,可以采用下面的方法。

在Oncreate()方法中加入者两句代码

StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

接着就可以尽情地使用下面编写的Http类了

一开始跟开发服务器那边的人在商量交互,两边必须说明传输方式,如用post还是get方式,必须一致才行。

对方给出了诸如此类的接口。

http://localhost:8080/CampusService/servlet/sendnews?client=0&user=1&pwd=1&text=123

http://localhost:8080/CampusService/servlet/getnews?client=0&user=1&pwd=1&count=2&from=0

等等之类的,想把信息交互作为一个模块,特地写了下面一个http类,采用post传输方式

package com.example.logic;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.content.Context;
import android.os.Environment;

import com.google.gson.JsonArray;

public class Http {
	private String base ;
	private String basepicture;

	public Http(Context context) {
		// TODO Auto-generated constructor stub
		FileService txt = new FileService(context);
		String str = null;
		try {
			str = txt.read(Environment.getExternalStorageDirectory() + "/ip.txt");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		base = "http://" + str + ":8080/CampusService";
		basepicture = "http://" + str + ":8080/CampusService/UploadImg.action";
	}
	public void upPhoto(String user,String pwd,String type,String str, String path){
		HttpClient httpClient = new DefaultHttpClient(); 
		httpClient.getParams().setParameter( CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1 );
		HttpPost httpPost = new HttpPost(basepicture);
		MultipartEntity postEntity = new MultipartEntity();
		// 字符用StringBody

		ContentBody cuser = null;
		ContentBody cpwd = null;
		ContentBody ctype = null;
		ContentBody cstr = null;
		ContentBody cclient = null;
		try {
			cuser = new StringBody(user);
			cpwd = new StringBody(pwd);
			ctype = new StringBody(type);
			cstr = new StringBody(str);
			cclient = new StringBody("0");

			String fileName = "/image.png";
			// ContentBody cbFileName = new StringBody( fileName );
			// 文件用FileBody,并指定文件类型
			File file = new File(path+fileName);
			ContentBody cbFileData = new FileBody(file, "image/png");
			// 把上面创建的这些Body全部加到Entity里面去。
			// 注意他们的key,这些key在Struts2服务器端Action的代码里必须保持一致!!
			postEntity.addPart("client",cclient);
			postEntity.addPart("user", cuser);
			postEntity.addPart("pwd", cpwd);
			postEntity.addPart("type", ctype);
			postEntity.addPart("str", cstr);
			postEntity.addPart("img", cbFileData);
			httpPost.setEntity(postEntity);
			// 下面这句话就把数据提交到服务器去了
			HttpResponse response = httpClient.execute(httpPost);
			// 打开response的数据流,就可以读取服务器端的回执数据
			InputStream reader = response.getEntity().getContent();
			BufferedReader breader = new BufferedReader(new InputStreamReader(reader));
			String readline = null;
			String result = "";
			while((readline = breader.readLine())!=null)
			{
				result += readline;
			}
			System.out.println(result);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public String addaction(String para){
		String baseurl = base + "/action/AddActivity.action?&client=1";
		String allurl = base + "/action/AddActivity.action?&client=1" + para;
		return basepost(baseurl, allurl);
	}
	public String changeComment(String para)
	{
    	
        String baseUrl = base + "/servlet/ChangeComment?&client=0";
        
        String allurl = base + "/servlet/ChangeComment?&client=0" + para;
        
        return basepost(baseUrl, allurl);
	}
	public String addfocususer(String para)
	{
    	
        String baseUrl = base + "/servlet/addfocus?&client=0";
        
        String allurl = base + "/servlet/addfocus?&client=0" + para;
        
        return basepost(baseUrl, allurl);
	} 
	public String search(String para)
	{
    	
        String baseUrl = base + "/servlet/searchuser?&client=0";
        
        String allurl = base + "/servlet/searchuser?&client=0" + para;
        
        return basepost(baseUrl, allurl);
	}
	public String register(JSONObject js)
	{
        String baseUrl = base + "/servlet/register";
        String allurl = "";
        try {
			allurl = base +  "/servlet/?&client=0&jsonuser="+java.net.URLEncoder.encode(js.toString(), "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		return basepost(baseUrl, allurl);
	}
	public String land(String para)
	{
		
        String baseUrl = base + "/servlet/login";
        String allurl = baseUrl + "/servlet/login?&client=0" + para;
		
		return basepost(baseUrl, allurl);
	}
    public String getnews(String para)
    {  	
        String baseUrl = base + "/servlet/getnews?&client=0";
        
        String strurl = base + "/servlet/getnews?&client=0" + para;
        
        return basepost(baseUrl, strurl);
    }
    public String sendnews(String text,String para)
    { 	
        String baseUrl = base + "/servlet/sendnews?&client=0";
        String allurl = "";
        try {
			allurl = base + "/servlet/sendnews?&client=0" + para + "&text=" + java.net.URLEncoder.encode(text, "UTF-8") ;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return basepost(baseUrl,allurl);
    }
    public String basepost(String baseUrl,String allurl){
    	String result = "";
    	try {
			URL url = new URL(baseUrl);
			System.out.println("运行到URL");
			try {
				HttpURLConnection urlcon = (HttpURLConnection)url.openConnection();
				urlcon.setDoInput(true);
				urlcon.setDoOutput(true);
				urlcon.setRequestMethod("POST");
				System.out.println("运行到post");
				urlcon.setUseCaches(false);
				urlcon.setInstanceFollowRedirects(true);
				urlcon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				urlcon.setRequestProperty("Charset", "UTF-8");
				System.out.println("connect");
				urlcon.connect();
				System.out.println("connect之后");		
				
				java.io.DataOutputStream d = new java.io.DataOutputStream(urlcon.getOutputStream());	
			//	String s = java.net.URLEncoder.encode(strurl, "UTF-8");
				d.writeBytes(allurl);
				d.flush();
				d.close();
				BufferedReader buf = new BufferedReader(new InputStreamReader(urlcon.getInputStream(),"UTF-8"));		
				String readLine = null;
				while( (readLine=buf.readLine()) != null){
					result += readLine;
				}
				System.out.println(result);
				buf.close();
				urlcon.disconnect();
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
			}
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			System.out.println("连接超时");
			e.printStackTrace();
		}
        return result;
    }
}
可能重构的不是很好,最主要的是蓝色部分的basepost()方法,其他函数只需要把参数传进来就可以了,都是调用basepost

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值