一 GET
String path = "http://v.juhe.cn/toutiao/index"; //接口地址
String parameter = "?type=&key=***"; //请求参数
try {
HttpClient client = new DefaultHttpClient(); //"客户端"
HttpGet get = new HttpGet(path + parameter);//get方式请求参数
HttpResponse response = client.execute(get);
if(response.getStatusLine().getStatusCode() == 200) { //获取链接状态
InputStream is = response.getEntity().getContent(); //获取输入流
String data = StreamTool.decodeStream(is); //StreamTool 代码附加在最后,用来把二进制流转换为字符流
JSONObject jsonObject = new JSONObject(data); //解析JSON格式数据
if("成功的返回".equals(jsonObject.getString("reason"))) {
JSONObject dataObject = jsonObject.getJSONObject("result");
JSONArray jsonArray = dataObject.getJSONArray("data");
Message msg = Message.obtain();
msg.obj = jsonArray;
msg.what = SECCESS;
mHandler.sendMessage(msg);
}else{
Message msg = Message.obtain();
msg.what = DATA_ERRER;
mHandler.sendMessage(msg);
}
}else{
Message msg = Message.obtain();
msg.what = CONNECT_ERRER;
mHandler.sendMessage(msg);
}
} catch (Exception e) {
Message msg = Message.obtain();
msg.what = ERRER;
mHandler.sendMessage(msg);
e.printStackTrace();
}
二 POST
在设置数据实体部分有些绕,需要理解记忆
参数key涉及个人隐私,所以用 ** 代替
String path = "http://v.juhe.cn/toutiao/index"; //接口地址
try {
HttpClient client = new DefaultHttpClient();// HttpClient是一个抽象类,new时需注意
HttpPost post = new HttpPost(path); //post请求方式 参数为接口地址
//设置 数据 实体
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("type", ""));
parameters.add(new BasicNameValuePair("key", "***"));
post.setEntity(new UrlEncodedFormEntity(parameters));
HttpResponse response = client.execute(post);
if(response.getStatusLine().getStatusCode() == 200){
InputStream is = response.getEntity().getContent();
String data = StreamTool.decodeStream(is); //StreamTool 代码附加在最后,用来把二进制流转换为字符流
JSONObject jsonObject = new JSONObject(data); //解析JSON格式数据
if("成功的返回".equals(jsonObject.getString("reason"))) {
JSONObject dataObject = jsonObject.getJSONObject("result");
JSONArray jsonArray = dataObject.getJSONArray("data");
Message msg = Message.obtain();
msg.obj = jsonArray;
msg.what = SECCESS;
mHandler.sendMessage(msg);
}else{
Message msg = Message.obtain();
msg.what = DATA_ERRER;
mHandler.sendMessage(msg);
}
}else{
Message msg = Message.obtain();
msg.what = CONNECT_ERRER;
mHandler.sendMessage(msg);
}
} catch (Exception e) {
Message msg = Message.obtain();
msg.what = ERRER;
mHandler.sendMessage(msg);
e.printStackTrace();
}
附加:StreamTool 类
public class StreamTool {
public static String decodeStream(InputStream is) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while((len = is.read(buffer))>0) {
bout.write(buffer, 0, len);
}
String data = bout.toString();
return data;
}
}