Android 调用WebAPI

来源:互联网 发布:文件收发管理系统源码 编辑:程序博客网 时间:2024/04/28 06:21
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;//超时时间//UPDATEpublic <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 ONEprivate Runnable getStudentRunnable=new Runnable() {@Overridepublic void run() {GetStudentByIdURL+="1";List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();JSONHttpClient jsonHttpClient = new JSONHttpClient();            StudentInfo item = jsonHttpClient.Get(GetStudentByIdURL, nameValuePairs, StudentInfo.class);}};//Searchprivate 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() {@Overridepublic 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);}};//UPDATEprivate Runnable updateStudentRunnable=new Runnable() {@Overridepublic 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);}};//DELETEprivate Runnable deleteStudentRunnable=new Runnable() {@Overridepublic void run() {List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();JSONHttpClient jsonHttpClient = new JSONHttpClient();DeleteStudentURL+="30";            boolean flag = jsonHttpClient.Delete(DeleteStudentURL, nameValuePairs);}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);int flag=5;switch (flag) {case 1://ADDnew Thread(addStudentsRunnable).start();break;case 2://UPDATEnew Thread(updateStudentRunnable).start();break;case 3://DELETEnew Thread(deleteStudentRunnable).start();break;case 4://SEARCHnew Thread(searchStudentsRunnable).start();break;case 5://GET ONEnew Thread(getStudentRunnable).start();break;default:break;}}@Overridepublic 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" />



0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 微快递下单不能定位怎么办 网上打字兼职被骗了怎么办 微信银行卡转错怎么办 在支付宝被诈骗怎么办 发现被骗了报警不理怎么办 投稿投错了网站怎么办 六个月宝宝吃辅食便秘怎么办 六个月宝宝加辅食后便秘怎么办 婴儿6个月便秘怎么办 7个月的孩子便秘怎么办 四个月宝宝喜欢吃手怎么办 博瑞智教育是上当了怎么办 我43岁记忆力差怎么办 艾灸灸出的湿疹怎么办 饭店合同到期房东不租怎么办 极端暴力控制不住自己怎么办 苹果已停止访问该网页怎么办 qq登陆后隐藏了怎么办 易班密码忘记了怎么办 老师上课讲错了怎么办 专升本差了一分怎么办 登录不上学信网怎么办 steam被好友删了怎么办 护士继续教育学分证丢了怎么办 护士证到期未延续注册怎么办 学籍和户口不在一起小升初怎么办 定了酒店不能退怎么办 去哪儿网酒店不允许取消怎么办 快递寄送身份证扣海关怎么办 7岁龋齿烂到牙根怎么办 法院判完对方说没钱怎么办 初中填完志愿后怎么办 上海小学借读一年级没有学籍怎么办 学历不高的我该怎么办 没学历的我该怎么办 物业达不到服务标准该怎么办 没有能力的人该怎么办 工作累了腰疼怎么办 机场来早了6小时怎么办 苏宁金融综合评分不足怎么办 苏宁金融秒拒怎么办