Android 调用WebAPI

1)准备工作
gson的下载地址如下
http://www.java2s.com/Code/Jar/g/gson.htm


下载后如何调用,这个问题对Android高手是多余的,但是很多新手应该还是需要讲解一下的

首先我们将gson-2.1.jar粘贴到项目的“libs”目录下,然后点击Eclipse的"Project"下的“Properties”选项卡,接下来选择左边的“Java Build Path”后在右边选择“Libraries”选项卡,单机“Add JARs...”按钮通过浏览到当前项目下的"libs"目录将gson-2.1添加。


2)创建类StudentInfo.java代码如下(类名和字段和WebAPI端保持一致)

package com.example.webapitest;

public class StudentInfo {
	private int stuId;
	private String stuName;
	private String stuAddress;
	
	public int getStuId() {
		return stuId;
	}
	public void setStuId(int stuId) {
		this.stuId = stuId;
	}
	public String getStuName() {
		return stuName;
	}
	public void setStuName(String stuName) {
		this.stuName = stuName;
	}
	public String getStuAddress() {
		return stuAddress;
	}
	public void setStuAddress(String stuAddress) {
		this.stuAddress = stuAddress;
	}
	public static final String STUDENT_NAME = "stuName";
    public static final String STUDENT_ADDRESS = "stuAddress";
}
3)创建调用WebAPI类JSONHttpClient代码如下

package com.example.webapitest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import com.google.gson.GsonBuilder;

public class JSONHttpClient {
	
	private int timeOut=5000;//超时时间
	//UPDATE
	public <T> T PutObject(String url, final T object, final Class<T> objectClass){
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        HttpPut httpPut=new HttpPut(url);
        try {
 
            StringEntity stringEntity = new StringEntity(new GsonBuilder().create().toJson(object));
            httpPut.setEntity(stringEntity);
            httpPut.setHeader("Accept", "application/json");
            httpPut.setHeader("Content-type", "application/json");
            httpPut.setHeader("Accept-Encoding", "gzip");
 
            defaultHttpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeOut);
            HttpResponse httpResponse = defaultHttpClient.execute(httpPut);
            if(httpResponse.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
            	return null;
            }
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                InputStream inputStream = httpEntity.getContent();
                Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding");
                if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                    inputStream = new GZIPInputStream(inputStream);
                }
 
                String resultString = convertStreamToString(inputStream);
                inputStream.close();
                return new GsonBuilder().create().fromJson(resultString, objectClass);
 
            }
 
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ClientProtocolException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }catch (Exception e) {
			e.printStackTrace();
		}
        return null;
    }
	//ADD
    public <T> T PostObject(final String url, final T object, final Class<T> objectClass) {
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        try {
 
            StringEntity stringEntity = new StringEntity(new GsonBuilder().create().toJson(object));
            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("Accept-Encoding", "gzip");
 
            defaultHttpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeOut);
            HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
            if(httpResponse.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
            	return null;
            }
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                InputStream inputStream = httpEntity.getContent();
                Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding");
                if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                    inputStream = new GZIPInputStream(inputStream);
                }
 
                String resultString = convertStreamToString(inputStream);
                inputStream.close();
                return new GsonBuilder().create().fromJson(resultString, objectClass);
            }
 
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ClientProtocolException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }catch (Exception e) {
			e.printStackTrace();
		}
        return null;
    }
 
    public <T> T PostParams(String url, final List<NameValuePair> params, final Class<T> objectClass) {
        String paramString = URLEncodedUtils.format(params, "utf-8");
        url += "?" + paramString;
        return PostObject(url, null, objectClass);
    }
 
    private String convertStreamToString(InputStream inputStream) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        try {
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        return stringBuilder.toString();
    }
    //GET
    public <T> T Get(String url, List<NameValuePair> params, final Class<T> objectClass) {
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        String paramString = URLEncodedUtils.format(params, "utf-8");
        url += "?" + paramString;
        HttpGet httpGet = new HttpGet(url);
        try {
            httpGet.setHeader("Accept", "application/json");
            httpGet.setHeader("Accept-Encoding", "gzip");
 
            defaultHttpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeOut);
            HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
            if(httpResponse.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
            	return null;
            }
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                InputStream inputStream = httpEntity.getContent();
                Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding");
                if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                    inputStream = new GZIPInputStream(inputStream);
                }
 
                String resultString = convertStreamToString(inputStream);
                inputStream.close();
                return new GsonBuilder().create().fromJson(resultString, objectClass);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ClientProtocolException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }catch (Exception e) {
			e.printStackTrace();
		}
        return null;
    }
    //DELETE
    public boolean Delete(String url, final List<NameValuePair> params) {
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        String paramString = URLEncodedUtils.format(params, "utf-8");
        url += "?" + paramString;
        HttpDelete httpDelete = new HttpDelete(url);
 
        HttpResponse httpResponse = null;
        try {
        	defaultHttpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeOut);
            httpResponse = defaultHttpClient.execute(httpDelete);
            if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
            	return true;
            }else {
				return false;
			}
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }catch (Exception e) {
			e.printStackTrace();
		}
        return false;
    }
}
4)修改MainActivity代码如下

package com.example.webapitest;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

	private static final String REST_SERVICE_URL = "http://10.0.9.75:88/api/";
	private static final String GetStudentsURL = REST_SERVICE_URL + "StudentValue/GetStudents";
	private static final String AddStudentURL=REST_SERVICE_URL+"StudentValue/AddStudent";
	private String UpdateStudentURL=REST_SERVICE_URL+"StudentValue/UpdateStudent/";
	private String DeleteStudentURL=REST_SERVICE_URL+"StudentValue/DeleteStudent/";
	private String GetStudentByIdURL=REST_SERVICE_URL+"StudentValue/GetStudentById/";
	//GET ONE
	private Runnable getStudentRunnable=new Runnable() {
		@Override
		public void run() {
			GetStudentByIdURL+="1";
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			JSONHttpClient jsonHttpClient = new JSONHttpClient();
            StudentInfo item = jsonHttpClient.Get(GetStudentByIdURL, nameValuePairs, StudentInfo.class);
		}
	};
	//Search
	private Runnable searchStudentsRunnable=new Runnable() {    
        @Override    
        public void run() {  
        	List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        	nameValuePairs.add(new BasicNameValuePair(StudentInfo.STUDENT_NAME, "chad"));
        	nameValuePairs.add(new BasicNameValuePair(StudentInfo.STUDENT_ADDRESS, ""));
            JSONHttpClient jsonHttpClient = new JSONHttpClient();
            StudentInfo[] items = jsonHttpClient.Get(GetStudentsURL, nameValuePairs, StudentInfo[].class);
        }    
    }; 
    //ADD
    private Runnable addStudentsRunnable=new Runnable() {
		@Override
		public void run() {
			StudentInfo studentInfo=new StudentInfo();
			studentInfo.setStuName("chad.cao");
			studentInfo.setStuAddress("zhejiang");
			JSONHttpClient jsonHttpClient = new JSONHttpClient();
            StudentInfo item = jsonHttpClient.PostObject(AddStudentURL, studentInfo, StudentInfo.class);
		}
	};
	//UPDATE
	private Runnable updateStudentRunnable=new Runnable() {
		@Override
		public void run() {
			UpdateStudentURL+="1";
			StudentInfo studentInfo=new StudentInfo();
			studentInfo.setStuName("chad11");
			studentInfo.setStuAddress("jiaxing11");
			JSONHttpClient jsonHttpClient=new JSONHttpClient();
			StudentInfo item=jsonHttpClient.PutObject(UpdateStudentURL,studentInfo , StudentInfo.class);
		}
	};
	//DELETE
	private Runnable deleteStudentRunnable=new Runnable() {
		@Override
		public void run() {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			JSONHttpClient jsonHttpClient = new JSONHttpClient();
			DeleteStudentURL+="30";
            boolean flag = jsonHttpClient.Delete(DeleteStudentURL, nameValuePairs);
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		int flag=5;
		switch (flag) {
		case 1://ADD
			new Thread(addStudentsRunnable).start();
			break;
		case 2://UPDATE
			new Thread(updateStudentRunnable).start();
			break;
		case 3://DELETE
			new Thread(deleteStudentRunnable).start();
			break;
		case 4://SEARCH
			new Thread(searchStudentsRunnable).start();
			break;
		case 5://GET ONE
			new Thread(getStudentRunnable).start();
			break;
		default:
			break;
		}
	}

	@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;
	}

}

5)为了能让Android调用网络数据在AndroidManifest.xml中添加代码如下

<uses-permission android:name="android.permission.INTERNET" />



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值