转载:www.androidkaifa.com
这是笔者我本人在工作中实际运用的一个能用android网络工具类(一部分),写不是很好,如哪个大牛可以为我指点指点,还请留言,谢谢,现在我把它在www.androidkaifa.com放出来,希望对需要的朋友有帮助,
public class ShopHttpTool { private static final String CHARSET = HTTP.UTF_8; private static HttpClient customerHttpClient; private static final String TAG="ShopHttpTool"; public static synchronized HttpClient getHttpClient() { if (null == customerHttpClient) { HttpParams params = new BasicHttpParams(); // 设置http协议版本 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, CHARSET); HttpProtocolParams.setUserAgent(params,"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83)"+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1"); ConnManagerParams.setTimeout(params, 100000); HttpConnectionParams.setConnectionTimeout(params, 100000); HttpConnectionParams.setSoTimeout(params, 100000); SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); //使用线程安全方式去管理创建HttpClient ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg); customerHttpClient = new DefaultHttpClient(conMgr, params); } return customerHttpClient; } //数据请求访问 public static InputStream postupload(String url, List<NameValuePair> formparams,UserBean user) throws Exception{ HttpResponse response; //将参数条件传入对象实体 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,CHARSET); // 创建POST请求 HttpPost request = new HttpPost(url); if(user==null){ request.addHeader("userid", "0"); request.addHeader("weblogid", ""); }else { request.addHeader("userid", user.getId()); request.addHeader("weblogid", user.getWeblogid()); } request.addHeader("Content-Type","application/x-www-form-urlencoded"); request.setEntity(entity); Log.i(TAG, request.getURI().getPath()); HttpClient client =new DefaultHttpClient(); response = client.execute(request); if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new RuntimeException("请求失败"); } HttpEntity resEntity = response.getEntity(); Log.i(TAG, "is success"); return (resEntity == null) ? null:resEntity.getContent(); } public static InputStream getupload(String url,Map<String, String> params,UserBean user)throws Exception{ StringBuilder sb = new StringBuilder(url); sb.append('?'); // ?method=save&title=435435435&timelength=89& for(Map.Entry<String, String> entry : params.entrySet()){ sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), "UTF-8")).append('&'); } sb.deleteCharAt(sb.length()-1); Log.i(TAG, sb.toString()); HttpGet httpget=new HttpGet(sb.toString()); httpget.addHeader("weblogid", user.getWeblogid()); if(user==null){ httpget.addHeader("userid", "0"); }else { httpget.addHeader("userid", user.getId()); } httpget.addHeader("Content-Type","application/x-www-form-urlencoded"); //取得HttpClient对象 HttpClient httpclient =getHttpClient(); //请求HttpClient,取得HttpResponse HttpResponse response = httpclient.execute(httpget); //请求成功 if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new RuntimeException("请求失败"); } HttpEntity resEntity = response.getEntity(); Log.i(TAG, "is success"); return (resEntity == null) ? null:resEntity.getContent(); } //SSL HTTPS Cookie public static InputStream sendRequestFromHttpClient(String path, Map<String, String> params,UserBean user) throws Exception{ List<NameValuePair> paramPairs = new ArrayList<NameValuePair>(); if(params!=null && !params.isEmpty()){ for(Map.Entry<String, String> entry : params.entrySet()){ paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity(paramPairs, CHARSET);//得到经过编码过后的实体数据 HttpPost post = new HttpPost(path); //form post.addHeader("weblogid", user.getWeblogid()); if(user==null){ post.addHeader("userid", "0"); }else { post.addHeader("userid", user.getId()); } post.addHeader("ContentType", "application/x-www-form-urlencoded"); post.setEntity(entitydata); DefaultHttpClient client = new DefaultHttpClient(); //浏览器 HttpResponse response = client.execute(post);//执行请求 if(response.getStatusLine().getStatusCode()==200){ Log.i(TAG, "is success"); return response.getEntity().getContent(); } return null; } public static InputStream sendPostRequest(String path, Map<String, String> params,UserBean user) throws Exception{ StringBuilder sb = new StringBuilder(); if(params!=null && !params.isEmpty()){ for(Map.Entry<String, String> entry : params.entrySet()){ sb.append(entry.getKey()).append('=') .append(URLEncoder.encode(entry.getValue(), CHARSET)).append('&'); } sb.deleteCharAt(sb.length()-1); } byte[] entitydata = sb.toString().getBytes();//得到实体的二进制数据 URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5 * 1000); conn.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据 //Content-Type: application/x-www-form-urlencoded //Content-Length: 38 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length)); conn.setRequestProperty("weblogid", user.getWeblogid()); if(user==null){ conn.setRequestProperty("userid", "0"); }else { conn.setRequestProperty("userid", user.getId()); } OutputStream outStream = conn.getOutputStream(); outStream.write(entitydata); outStream.flush(); outStream.close(); if(conn.getResponseCode()==200){ Log.i(TAG, "is success"); return conn.getInputStream(); } return null; } public static InputStream sendGetRequest(String path, Map<String, String> params,UserBean user) throws Exception{ StringBuilder sb = new StringBuilder(path); sb.append('?'); // ?method=save&title=435435435&timelength=89& for(Map.Entry<String, String> entry : params.entrySet()){ sb.append(entry.getKey()).append('=') .append(URLEncoder.encode(entry.getValue(), CHARSET)).append('&'); } sb.deleteCharAt(sb.length()-1); byte[] entitydata = sb.toString().getBytes();//得到实体的二进制数据 URL url = new URL(sb.toString()); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length)); conn.setRequestProperty("weblogid", user.getWeblogid()); if(user==null){ conn.setRequestProperty("userid", "0"); }else { conn.setRequestProperty("userid", user.getId()); } conn.setConnectTimeout(5 * 1000); if(conn.getResponseCode()==200){ Log.i(TAG, "is success"); return conn.getInputStream(); } return null; } public static byte[] readStream(InputStream inStream){ ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); try { byte[] buffer = new byte[1024]; int len = -1; while( (len=inStream.read(buffer)) != -1){ outSteam.write(buffer, 0, len); } outSteam.close(); inStream.close(); } catch (IOException e) { Log.w(TAG, e.getMessage()); } return outSteam.toByteArray(); } }