android httpclient基本用法

来源:互联网 时间:1970-01-01

android  httpclient常用的post get delete put 方法简单使用

传值方式:文本键值对格式 和 json格式


/** * 通过Put方式发送请求 更新采集器信息 * @param url URL地址 * @param params 参数 * @return * @throws Exception */ public String httpPut(String json,String url, List<Parameter> params, String tokenAuth,int type) throws Exception { String response = null; int timeoutConnection = YunTongXun.httpclienttime; int timeoutSocket = YunTongXun.httpclienttime; HttpParams httpParameters = new BasicHttpParams();// Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); // 构造HttpClient的实例 HttpClient httpClient = new DefaultHttpClient(httpParameters); HttpPut httpPost = new HttpPut(url); if (params.size()>=0) { //设置httpPost请求参数 if(type==2) { String jsstr = "[{"; for (Parameter param : params) { jsstr += "/"" + param.getName() +"/":" + param.getValue() + ","; } jsstr = jsstr.substring(0,jsstr.length()-1); jsstr +="}]"; if(json!=null) { jsstr = json; } System.out.println(jsstr); StringEntity s = new StringEntity(jsstr ,"utf-8"); s.setContentEncoding("UTF-8"); s.setContentType("text/json"); s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httpPost.setEntity(s); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-Type","application/json;charset=UTF-8"); } else if(type==3) { boolean isLock = false,hasMutiDistance = false; String blowerIds = ""; String distances = ""; for (Parameter param : params) { if(param.getName().equals("distance")) { if(param.getValue().split(",").length>1) { distances = param.getValue(); hasMutiDistance = true; } } else if(param.getName().equals("lock")) { if(param.getValue().length()>2) { blowerIds = param.getValue(); isLock = true; } } else if(param.getName().equals("unlock")) { if(param.getValue().length()>2) { blowerIds = param.getValue(); isLock = false; } } } if(!hasMutiDistance) { String jsstr = "[{"; for (Parameter param : params) { jsstr += "/"" + param.getName() +"/":" + param.getValue() + ","; } jsstr = jsstr.substring(0,jsstr.length()-1); jsstr +="}]"; StringEntity s = new StringEntity(jsstr ,"utf-8"); s.setContentEncoding("UTF-8"); s.setContentType("text/json"); s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httpPost.setEntity(s); } else { String jsstr = "["; int i =0; blowerIds = blowerIds.replace("[", "").replace("]", ""); for(String dis : distances.split(",")) { if(isLock) { jsstr += "{/"distance/":" + dis + ",/"lock/":[" + blowerIds.split(",")[i] + "],/"unlock/":[]},"; } else { jsstr += "{/"distance/":" + dis + ",/"unlock/":[" + blowerIds.split(",")[i] + "],/"lock/":[]},"; } i++; } jsstr = jsstr.substring(0,jsstr.length()-1); jsstr +="]"; System.out.println(jsstr); StringEntity s = new StringEntity(jsstr ,"utf-8"); s.setContentEncoding("UTF-8"); s.setContentType("text/json"); s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httpPost.setEntity(s); } httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-Type","application/json;charset=UTF-8"); } else if(type ==1) { httpPost.setEntity(new UrlEncodedFormEntity(buildNameValuePair(params),HTTP.UTF_8)); } } if(tokenAuth != null) httpPost.setHeader("Authorization", tokenAuth); //使用execute方法发送HTTP Post请求,并返回HttpResponse对象 HttpResponse httpResponse = httpClient.execute(httpPost); int statusCode = httpResponse.getStatusLine().getStatusCode(); if(statusCode==HttpStatus.SC_CREATED || statusCode == HttpStatus.SC_OK) { //获得返回结果 response = EntityUtils.toString(httpResponse.getEntity(),"utf-8"); if(response==null || response.length()<2) { System.out.println("{status_code:"+statusCode+"}"); return "{status_code:"+statusCode+"}"; } } else { response = EntityUtils.toString(httpResponse.getEntity(),"utf-8"); System.out.println(response); System.out.println("{status_code:"+statusCode+"}"); return "{status_code:"+statusCode+"}"; } return response; }



/** * http通信类 * @author sm * */@SuppressWarnings("deprecation")public class SyncHttp{/*** 通过GET方式发送请求* @param url URL地址* @param params 参数* @return * @throws Exception*/public String httpGet(String url, String params) throws Exception{String response = null; //返回信息//拼接请求URLif (null!=params&&!params.equals("")){url += "?" + params;}int timeoutConnection = YunTongXun.httpclienttime; int timeoutSocket = YunTongXun.httpclienttime;HttpParams httpParameters = new BasicHttpParams();// Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); // 构造HttpClient的实例HttpClient httpClient = new DefaultHttpClient(httpParameters); // 创建GET方法的实例HttpGet httpGet = new HttpGet(url);try{HttpResponse httpResponse = httpClient.execute(httpGet);int statusCode = httpResponse.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) //SC_OK = 200{// 获得返回结果response = EntityUtils.toString(httpResponse.getEntity(),"utf-8");}else{return "{status_code:"+statusCode+"}";}} catch (Exception e){return null;} return response;}/*** 通过POST方式发送请求 获取短信* @param url URL地址* @param params 参数* @return* @throws Exception*/public String httpPost(String url, List<Parameter> params) throws Exception{String response = null;int timeoutConnection = YunTongXun.httpclienttime; int timeoutSocket = YunTongXun.httpclienttime; HttpParams httpParameters = new BasicHttpParams();// Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); // 构造HttpClient的实例HttpClient httpClient = new DefaultHttpClient(httpParameters); HttpPost httpPost = new HttpPost(url);if (params.size()>=0){//设置httpPost请求参数httpPost.setEntity(new UrlEncodedFormEntity(buildNameValuePair(params),HTTP.UTF_8));}//使用execute方法发送HTTP Post请求,并返回HttpResponse对象HttpResponse httpResponse = httpClient.execute(httpPost);int statusCode = httpResponse.getStatusLine().getStatusCode();if(statusCode==HttpStatus.SC_CREATED || statusCode == HttpStatus.SC_OK){//获得返回结果 response = EntityUtils.toString(httpResponse.getEntity(),"utf-8");}else{ return "{status_code:"+statusCode+"}";}return response;}/*** 把Parameter类型集合转换成NameValuePair类型集合* @param params 参数集合* @return*/private List<BasicNameValuePair> buildNameValuePair(List<Parameter> params){List<BasicNameValuePair> result = new ArrayList<BasicNameValuePair>();for (Parameter param : params){BasicNameValuePair pair = new BasicNameValuePair(param.getName(), param.getValue());result.add(pair);}return result;}/*** 通过delete方式发送请求* @param url URL地址* @param params 参数* @return * @throws Exception*/public String httpdelete(String url, String params) throws Exception{String response = null; //返回信息//拼接请求URLif (null!=params&&!params.equals("")){url += "?" + params;}int timeoutConnection = YunTongXun.httpclienttime; int timeoutSocket = YunTongXun.httpclienttime; HttpParams httpParameters = new BasicHttpParams();// Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); // 构造HttpClient的实例HttpClient httpClient = new DefaultHttpClient(httpParameters); // 创建GET方法的实例HttpDelete httpdelete = new HttpDelete(url);try{HttpResponse httpResponse = httpClient.execute(httpdelete);int statusCode = httpResponse.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) //SC_OK = 200{// 获得返回结果response = EntityUtils.toString(httpResponse.getEntity(),"utf-8");}else{return "{status_code:"+statusCode+"}";}} catch (Exception e){return null;} return response;}/*** 通过put方式发送请求,修改用户信息* @param url URL地址* @param params 参数* @return * @throws Exception*/public String httpPut(String url, HashMap<String, String> params,String tokenAuth) throws Exception{String response = null; //返回信息//拼接请求URLint timeoutConnection = YunTongXun.httpclienttime; int timeoutSocket = YunTongXun.httpclienttime; HttpParams httpParameters = new BasicHttpParams();// Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); // 构造HttpClient的实例HttpClient httpClient = new DefaultHttpClient(httpParameters);// 创建GET方法的实例HttpPut httpPut = new HttpPut(url);httpPut.setHeader("Authorization", tokenAuth);if (params.size()>=0){MultipartEntity reqEntity = new MultipartEntity();if(params.keySet().contains("password")){reqEntity.addPart("password", new StringBody(params.get("password"),Charset.forName("UTF-8")));reqEntity.addPart("username", new StringBody(params.get("username"),Charset.forName("UTF-8")));reqEntity.addPart("new_password", new StringBody(params.get("new_password"),Charset.forName("UTF-8")));}else{ // reqEntity.addPart("username", new StringBody(params.get("username"),Charset.forName("UTF-8")));if(params.keySet().contains("nickname")){ reqEntity.addPart("nickname", new StringBody(params.get("nickname"),Charset.forName("UTF-8")));}if(params.keySet().contains("avatar")){reqEntity.addPart("avatar", new FileBody(new File(params.get("avatar"))));}}//设置httpPost请求参数 httpPut.setEntity(reqEntity);}try{HttpResponse httpResponse = httpClient.execute(httpPut);int statusCode = httpResponse.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) //SC_OK = 200{// 获得返回结果response = EntityUtils.toString(httpResponse.getEntity(),"utf-8");}else{return "{status_code:"+statusCode+"}";}} catch (Exception e){return null;} return response;}/*** 通过put方式发送请求,修改用户密码信息* @param url URL地址* @param params 参数* @return * @throws Exception*/public String httpPutSetNewPwd(String url, HashMap<String, String> params) throws Exception{String response = null; //返回信息//拼接请求URLint timeoutConnection = YunTongXun.httpclienttime; int timeoutSocket = YunTongXun.httpclienttime; HttpParams httpParameters = new BasicHttpParams();// Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);// Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); // 构造HttpClient的实例HttpClient httpClient = new DefaultHttpClient(httpParameters);// 创建GET方法的实例HttpPut httpPut = new HttpPut(url);if (params.size()>=0){MultipartEntity reqEntity = new MultipartEntity();reqEntity.addPart("code", new StringBody(params.get("code"),Charset.forName("UTF-8")));reqEntity.addPart("username", new StringBody(params.get("username"),Charset.forName("UTF-8")));reqEntity.addPart("new_password", new StringBody(params.get("new_password"),Charset.forName("UTF-8")));//设置httpPost请求参数 httpPut.setEntity(reqEntity);}try{HttpResponse httpResponse = httpClient.execute(httpPut);int statusCode = httpResponse.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) //SC_OK = 200{// 获得返回结果response = EntityUtils.toString(httpResponse.getEntity(),"utf-8");}else{return "{status_code:"+statusCode+"}";}} catch (Exception e){return null;} return response;}}








相关阅读:
Top