Android 调用WebAPI
来源:互联网 发布:文件收发管理系统源码 编辑:程序博客网 时间:2024/04/28 06:21
1)准备工作
gson的下载地址如下
http://www.java2s.com/Code/Jar/g/gson.htm
5)为了能让Android调用网络数据在AndroidManifest.xml中添加代码如下
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
- Android 调用WebAPI
- 调用webapi
- webApi调用
- ANDROID调用VS2013 ASP.NET WEBAPI 返回DATATABLE 注意
- Angular 调用 WebApi 传参
- HttpClient 调用WebApi
- web端跨域调用webapi
- WebApi 跨域调用
- 调用 Webapi 跨域
- c# 调用webApi
- WEBAPI实体参数调用
- java 调用 C# webapi
- C# 调用WebApi
- C#调用webApi方法
- angulerjs调用webapi CORS
- 调用 Webapi 跨域
- 调用webapi的方法
- WebApi(6) 后台C#调用WebApi
- 派生类的初始化列表
- STM32相关(基于libopencm3库)
- 一步步教你为网站开发Android客户端
- 控件笔记之鸡啄米
- linux添加环境变量的方法总结
- Android 调用WebAPI
- HBase 学习一: 客户端写缓冲区 autoFlush
- android bitmap 缓存工具类
- Centos设置静态IP
- c++基础学习3-c++中的函数a
- Cocos2dx 配置的环境需求
- 动态规划:矿工模型
- my_itob
- POJ 2451 Uyuw's Concert