您的位置:首页 > 理论基础 > 计算机网络

android利用httpclient实现post、get请求restful接口进行json和form表单数据提交等公共方法类

2017-01-12 15:51 2201 查看
根据项目经验和自己常用的接口类型,编写了一个公共类,让原生android进行网络数据请求更加方便。

这个方法处理的情况如下:

1、利用httpclient协议进行通信(httpurlconnection 太类似)

2、进行post和get请求

3、接口接收参数有json格式和form表单格式的数据。

4、我会把接口形式也展现出来。至于怎样配置两种形式的restful接口。我就不说了

下面开始代码:

1、按钮调用不同的请求方式



可以看到我进行了四种方式的请求

按钮事件添加如下:

@Override
public void onClick(View viewid) {
// TODO Auto-generated method stub
switch (viewid.getId()) {
case R.id.btn11:
{intent.setClass(MainActivity.this, LoadProgressBar.class);
startActivity(intent);
break;}

case R.id.btn12:
{
String st="http://10.20.126.239:8089/gwm_web/services/Api/LoginPost";//json接口
Map<String, Object> map = new LinkedHashMap<String, Object>(); 
map.put("loginName", "dhj");
map.put("loginPw", "123456");
   httpclient=new HttpClientClass(st, "POST", "JSON", map,handle);
httpclient.start();
break;}

case R.id.btn13:
{
String st="http://10.20.126.239:8089/ApiTest/rest/Api/LoginPost";//form表单接口
Map<String, Object> map = new LinkedHashMap<String, Object>(); 
map.put("loginName", "dhj");
map.put("loginPw", "123456");
   httpclient=new HttpClientClass(st, "POST", "Form", map,handle);
httpclient.start();
break;}
case R.id.btn21:
{
String st="http://10.20.126.239:8089/gwm_web/services/Api/LoginGet/DHJ/123456";//json接口
Map<String, Object> map = new LinkedHashMap<String, Object>();
   httpclient=new HttpClientClass(st, "GET", "JSON", map,handle);
httpclient.start();
break;}
case R.id.btn22:
{
String st="http://10.20.126.239:8089/ApiTest/rest/Api/LoginGet";//form表单接口
Map<String, Object> map = new LinkedHashMap<String, Object>(); 
map.put("loginName", "DHJ");
map.put("loginPw", "123456");
   httpclient=new HttpClientClass(st, "GET", "Form", map,handle);
httpclient.start();
break;}

default:
break;
}
}

可以看到  httpclient=new HttpClientClass(st, "POST", "Form", map,handle);我是把公共类做成了子线程的形式,是不是又减轻你的工作量一点点,具体说一下参数的内容

st是你要连接的接口地址,第二个参数有post和get两种代表你是机进行post还是get请求。第三个参数代表是进行json格式数据提交还是form表单提交第四个参数主要是用来获取子线程返回结果的获取,子线程和主线程用handler进行通信。

下面就是看看我写的公共类

package com.dhj.base.network;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.UnsupportedEncodingException;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.ProtocolException;

import java.net.URL;

import java.net.URLEncoder;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.LinkedHashMap;

import java.util.List;

import java.util.Map;

import java.util.Set;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

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.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicNameValuePair;

import org.json.JSONException;

import org.json.JSONObject;

import android.os.Handler;

import android.os.Message;

import android.util.Log;

public class HttpClientClass extends Thread {
private String requestStyle;
private String dataStyle;
private String url;
String result = null;
private Handler handle;
Map<String, Object> map = new LinkedHashMap<String, Object>(); 

/**
* @author gw00093437 dhj 2017.1.10
* @param url
*            接口地址
* @param requestStyle
*            请求类型GET\POST
* @param dataStyle
*            数据提交方式FORM\JSON
* @param map
*            数据源供转化解析
* @param handle
* 返回数据的存储
*/
public HttpClientClass(String url, String requestStyle, String dataStyle,
Map map,Handler handle) {
this.requestStyle = requestStyle;
this.dataStyle = dataStyle;
this.url = url;
this.map = map;
this.handle=handle;
}

@Override
public void run() {
// 创建httpclient对象
HttpClient httpclient = new DefaultHttpClient();
// 首先判断请求类型
if (requestStyle.equals("GET")) {
// GET方式
String param="";
Iterator it = map.keySet().iterator();
String key;
String value;
HttpGet get;
while (it.hasNext()) {
key = it.next().toString();
value = (String) map.get(key);
if(param==""){
param=key+"="+value;
}else{
param=param+"&"+key+"="+value;
}

}
BufferedReader in = null;
String content=null;
if(param==""){
get = new HttpGet(url);
}else{
get = new HttpGet(url+"?"+param);
}

try {
HttpResponse response=httpclient.execute(get);
in = new BufferedReader(new InputStreamReader(response.getEntity()  
                   .getContent()));  
           StringBuffer sb = new StringBuffer("");  
           String line = "";  
           String NL = System.getProperty("line.separator");  
           while ((line = in.readLine()) != null) {  
               sb.append(line + NL);  
           }  
           in.close();  
           content = sb.toString();
Message msg = new Message();

                    msg.obj= content;

                    handle.sendMessage(msg);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
// POST方式
HttpPost post = new HttpPost(url);
// 判断数据提交类型
if (dataStyle.equals("JSON")) {
// json数据类型进行提交
JSONObject jsonParam = new JSONObject();
Iterator it = map.keySet().iterator();
String key;
String value;
while (it.hasNext()) {
key = it.next().toString();
value = (String) map.get(key);
try {
jsonParam.put(key, value);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
StringEntity jsonentity = null;
try {
jsonentity = new StringEntity(jsonParam.toString(), "utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}// 解决中文乱码问题
jsonentity.setContentEncoding("UTF-8");
jsonentity.setContentType("application/json");
post.setEntity(jsonentity);
HttpResponse response = null;
try {
response = httpclient.execute(post);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (response.getStatusLine().getStatusCode() == 200) {
// 第五步:从相应对象当中取出数据,放到entity当中
HttpEntity entity = response.getEntity();
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(entity.getContent()));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

try {
result = reader.readLine();
 Message msg = new Message();

                          msg.obj= result;

         
c5c1
                handle.sendMessage(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("dhj", "POST_JSON:" + result);
}

} else {
// form表单形式的数据进行提交 解析map数据
int size = map.size();
// 利用KeySet 迭代
List<NameValuePair> params = new ArrayList<NameValuePair>();
Iterator it = map.keySet().iterator();
String key;
String value;
while (it.hasNext()) {
key = it.next().toString();
value = (String) map.get(key);
params.add(new BasicNameValuePair(key, value));
}
HttpEntity requestEntity = null;
try {
requestEntity = new UrlEncodedFormEntity(params);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} // 将请求体放置到请求对象中
post.setEntity(requestEntity); // 执行请求对象 form表单的形式/
HttpResponse response = null;
try {
response = httpclient.execute(post);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (response.getStatusLine().getStatusCode() == 200) {
// 第五步:从相应对象当中取出数据,放到entity当中
HttpEntity entity = response.getEntity();
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(entity.getContent()));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

try {
result = reader.readLine();
 Message msg = new Message();

                        msg.obj= result;

                        handle.sendMessage(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("dhj", "POST_Form:" + result);
}
}

}
super.run();
}

}

如果想捕获每个节点的异常可以继续添加代码。详细我就不给大家解析了,自己能分析明白的。

给大家看一下我的接口:

1、json格式的接口

@Path("Api")

public class ApiTest {
@POST
@Path("LoginPost")
@Produces("application/json")
@Consumes( { "application/json" })
public JSONObject LoginPost(UserInfo user)
throws JSONException {
JSONObject o=new JSONObject();
o.put("Json_post_name", user.getLoginName());
System.out.println("Json_post_name:"+user.getLoginName()+"&&"+user.getLoginPw());
return o;
}
@GET
@Path("LoginGet/{loginName}/{loginPw}")
@Produces("application/json")
@Consumes( { "application/json" })
public JSONObject LoginGet(@PathParam("loginName") String loginName,@PathParam("loginPw") String loginPw)
throws JSONException {
JSONObject o=new JSONObject();
o.put("Json_get_name", loginName);
System.out.println("Json_get_name:"+loginName+"&&"+loginPw);
return o;
}

}

2、form表单格式的接口。spring mvc中的架构

@Controller

@RequestMapping("/Api")

public class PostApi {
@RequestMapping(value = "/LoginGet", method = RequestMethod.GET)
public JSONObject LoginGet( HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF-8");
String name=request.getParameter("loginName");
String pwd = request.getParameter("loginPw");
System.out.println("Form_GET:name"+name+"&&pwd"+pwd);
printJson(response,"name");
return null;
}
@RequestMapping(value = "/LoginPost", method = RequestMethod.POST)
public JSONObject LoginPost( HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF-8");
String name=request.getParameter("loginName");
String pwd = request.getParameter("loginPw");
System.out.println("Form_POST:name"+name+"&&pwd"+pwd);
printJson(response,"name");
return null;
}
private void printJson(HttpServletResponse response, String jsonStr) {
try {
response.setContentType("application/json;charset=UTF-8");
response.getWriter().print(jsonStr);
} catch (Exception e) {
e.printStackTrace();
}
}

}

get和post共四种情况、哈哈。不足之处多多包涵。时间匆忙只是自己进行验证没问题,没有进行更深的丰富,比如asp.net的web接口也包涵进来,用soap协议,进行json和xml数据通信等。大家自己丰富吧
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐