package com.api.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import android.util.Log;
import com.api.demo.model.State;
import com.api.demo.util.LogUtil;
import com.api.demo.util.PropertiesUtil;
import com.google.gson.Gson;
/**
*
* Restful 客户端类
*
* @author Chasel.li
*
*/
public class RestTemplate {
private static final String LOGTAG = LogUtil.makeLogTag(RestTemplate.class);
private HttpClient client = null;
private String url = PropertiesUtil.getUrl();
private Gson gson;
private static List<State> states;
public RestTemplate () {
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 50 * 1000);
HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);
client = new DefaultHttpClient(httpParams);
gson = new Gson();
}
/**
* Restful get请求,可用{@link packageUri}对url进行参数的封装
* @return
*/
public String httpGetDemo() {
HttpGet httpGet = new HttpGet(url);
HttpResponse response = null;
StringBuffer result = new StringBuffer();
try {
response = client.execute(httpGet);
} catch (ClientProtocolException e) {
return "httpGetDemo Request ClientProtocolException :" + e.getMessage();
} catch (IOException e) {
return "httpGetDemo Request IOException :" + e.getMessage();
}
try {
InputStream inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String responseResult = "";
while ((responseResult = reader.readLine()) != null) {
result.append(responseResult);
}
reader.close();
} catch (IllegalStateException e) {
return "httpGetDemo Response IllegalStateException" + e.getMessage();
} catch (IOException e) {
return "httpGetDemo Response IOException" + e.getMessage();
}
Log.i(LOGTAG, result.toString());
return result.toString();
}
/**
* Restful post请求, 可以使用{@code HttpEntity}对参数进行封装
* @return
*/
public String httpPostDemo() {
StringBuffer result = new StringBuffer();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = null;
HttpEntity httpEntity = null;
final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add(new BasicNameValuePair("states", gson.toJson(getStates())));
try {
httpEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
return "HttpPostDemo request httpEntity UnsupportedEncodingException:" + e.getMessage();
}
httpPost.setEntity(httpEntity);
try {
response = client.execute(httpPost);
} catch (ClientProtocolException e) {
return "httpPostDemo Request ClientProtocolException:" + e.getMessage();
} catch (IOException e) {
return "httpPostDemo Request IOException" + e.getMessage();
}
try {
InputStream inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String responseResult = "";
while ((responseResult = reader.readLine()) != null) {
result.append(responseResult);
}
reader.close();
} catch (IllegalStateException e) {
return "httpPostDemo Response IllegalStateException:" + e.getMessage();
} catch (IOException e) {
return "httpPostDemo Response IOException" + e.getMessage();
}
Log.i(LOGTAG, result.toString());
return result.toString();
}
/**
* Restful put请求, 可以使用{@code HttpEntity}对参数进行封装,
* 该方法的url用httpEntity封装,参数会出现问题, 直接拼装URl服务器会正确返回,
* 如果要使用httpEntity进行参数的封装, 请注意该问题
* @return 返回服务器端数据
*/
public String httpPutDemo() {
StringBuffer result = new StringBuffer();
HttpPut httpPut = new HttpPut(url+"?state=hello");
HttpResponse response = null;
HttpEntity httpEntity = null;
final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
State state = new State();
state.setName("南京");
state.setAbbreviation("NJ");
params.add(new BasicNameValuePair("state", gson.toJson(state)));
try {
httpEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
return "httpPutDemo request httpEntity UnsupportedEncodingException:" + e.getMessage();
}
// httpPut.setEntity(httpEntity);
try {
response = client.execute(httpPut);
} catch (ClientProtocolException e) {
return "httpPutDemo Request ClientProtocolException";
} catch (IOException e) {
return "httpPutDemo Request IOException";
}
try {
InputStream inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String responseResult = "";
while ((responseResult = reader.readLine()) != null) {
result.append(responseResult);
}
reader.close();
} catch (IllegalStateException e) {
return "httpPutDemo Response IllegalStateException:" + e.getMessage();
} catch (IOException e) {
return "httpPutDemo Response IOException:" + e.getMessage();
}
Log.i(LOGTAG, result.toString());
return result.toString();
}
/**
* Restful delete请求
* @return 返回服务器端数据
*/
public String httpDeleteDemo() {
StringBuffer result = new StringBuffer();
final Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");
HttpDelete httpDelete = new HttpDelete(packageUri(url, params));
HttpResponse response = null;
try {
response = client.execute(httpDelete);
} catch (ClientProtocolException e) {
return "httpDeleteDemo Request ClientProtocolException:" + e.getMessage();
} catch (IOException e) {
return "httpDeleteDemo Request IOException:" + e.getMessage();
}
try {
InputStream inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String responseResult = "";
while ((responseResult = reader.readLine()) != null) {
result.append(responseResult);
}
reader.close();
} catch (IllegalStateException e) {
return "httpDeleteDemo Response IllegalStateException:" + e.getMessage();
} catch (IOException e) {
return "httpDeleteDemo Response IOException:" + e.getMessage();
}
Log.i(LOGTAG, result.toString());
return result.toString();
}
/**
* 封装URL, 在get和delete请求中不能使用{@code HttpEntity}封装参数, 用该方法封装
* @param uri 原始uri
* @param params 请求参数列表
* @return 原始uri和参数组成的新uri
*/
@SuppressWarnings("rawtypes")
public String packageUri(String uri, Map<String, String> params) {
String paramStr = "";
Iterator<?> iter = params.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String key = entry.getKey().toString();
String val = entry.getValue().toString();
try {//在请求参数中,值是中文时必须要进行UTF-8的转码
paramStr +=
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
android_resptful_demo.zip (41个子文件)
android_resptful_demo
bin
classes.dex 314KB
res
drawable-ldpi
icon.png 2KB
drawable-hdpi
icon.png 5KB
drawable-mdpi
icon.png 3KB
classes
com
api
demo
BuildConfig.class 333B
RestTemplateTest.class 900B
R$layout.class 376B
R$drawable.class 382B
HelloAndroidActivity.class 745B
model
State.class 883B
R$attr.class 322B
R.class 453B
RestTemplate.class 9KB
R$string.class 409B
util
PropertiesUtil.class 1KB
PropertiesUtilTest.class 802B
LogUtil.class 798B
resources.ap_ 12KB
demo.apk 148KB
AndroidManifest.xml 965B
pom.xml 2KB
res
drawable-ldpi
icon.png 3KB
drawable-hdpi
icon.png 6KB
values
strings.xml 152B
drawable-mdpi
icon.png 4KB
layout
main.xml 382B
assets
demo.properties 49B
gen
com
api
demo
BuildConfig.java 154B
R.java 634B
.settings
org.eclipse.core.resources.prefs 88B
src
test
java
com
api
demo
RestTemplateTest.java 449B
util
PropertiesUtilTest.java 330B
main
java
com
api
demo
RestTemplate.java 9KB
model
State.java 574B
HelloAndroidActivity.java 702B
util
PropertiesUtil.java 575B
LogUtil.java 209B
.project 1016B
.classpath 861B
project.properties 563B
AndroidManifest.xml 965B
共 41 条
- 1
huangxiang
- 粉丝: 0
- 资源: 4
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
- 1
- 2
- 3
前往页