package com.maidong.utils;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLConnection;import java.net.URLDecoder;import java.net.URLEncoder;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.apache.http.HttpEntity;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.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.protocol.HTTP;import android.app.Activity;import android.content.Context;import android.net.ConnectivityManager;import android.net.NetworkInfo;public class InternetUtils { private static final String USER_AGENT = "User-Agent"; public static String httpPost(String url, List<NameValuePair> nameValuePairs) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); // List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); // Your DATA // nameValuePairs.add(new BasicNameValuePair("id", "12345")); // nameValuePairs.add(new BasicNameValuePair("stringdata", // "eoeAndroid.com is Cool!")); httpPost.setHeader(USER_AGENT, "Mozilla/4.5"); HttpEntity httpEntity = null; try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8)); httpEntity = httpclient.execute(httpPost).getEntity(); } finally { //httpPost.abort(); } return retrieveHttpEntity(httpEntity); } public static InputStream download(URL url) throws IOException { URLConnection conn = url.openConnection(); InputStream is = conn.getInputStream(); return is; } public static byte[] downloadFileData(String surl) throws IOException { URL url = new URL(surl); URLConnection conn = url.openConnection(); // 获取长度 int length = (int) conn.getContentLength(); InputStream is = conn.getInputStream(); byte[] imgData = null; if (length != -1) { imgData = new byte[length]; byte[] temp = new byte[512]; int readLen = 0; int destPos = 0; while ((readLen = is.read(temp)) > 0) { System.arraycopy(temp, 0, imgData, destPos, readLen); destPos += readLen; } } return imgData; } public static InputStream download(String url) throws IOException { return download(new URL(url)); } public static String httpPost(String url) throws ClientProtocolException, IOException { return httpPost(url, new ArrayList<NameValuePair>()); } private static String retrieveHttpEntity(HttpEntity httpEntity) throws UnsupportedEncodingException, IllegalStateException, IOException { StringBuffer stringBuffer = new StringBuffer(); InputStreamReader is = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8); BufferedReader bufferedReader = new BufferedReader(is); String line; while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line); } return stringBuffer.toString(); } public static String uploadFile(String actionUrl, String newName, InputStream fStream) { String end = "\r\n"; String twoHyphens = "--"; String boundary = java.util.UUID.randomUUID().toString(); DataOutputStream ds = null; try { URL url = new URL(actionUrl); HttpURLConnection con = (HttpURLConnection) url.openConnection(); /* 允许Input、Output,不使用Cache */ con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); /* 设定传送的method=POST */ con.setRequestMethod("POST"); /* setRequestProperty */ con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); /* 设定DataOutputStream */ ds = new DataOutputStream(con.getOutputStream()); ds.writeBytes(twoHyphens + boundary + end); ds.writeBytes("Content-Disposition: form-data; " + "name=\"Filedata\";filename=\"" + newName + "\"" + end); ds.writeBytes(end); /* 取得文件的FileInputStream */ // FileInputStream fStream = new FileInputStream(uploadFile); /* 设定每次写入1024bytes */ int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int length = -1; /* 从文件读取数据到缓冲区 */ while ((length = fStream.read(buffer)) != -1) { /* 将数据写入DataOutputStream中 */ ds.write(buffer, 0, length); } ds.writeBytes(end); ds.writeBytes(twoHyphens + boundary + twoHyphens + end); ds.flush(); /* 取得Response内容 */ InputStream is = con.getInputStream(); int ch; StringBuffer b = new StringBuffer(); while ((ch = is.read()) != -1) { b.append((char) ch); } /* 将Response显示于Dialog */ // showDialog(b.toString().trim()); return b.toString().trim(); /* 关闭DataOutputStream */ } catch (Exception e) { // showDialog("" + e); } finally { AppUtils.close(ds); AppUtils.close(fStream); } return null; } /** * * @param s * @return null if the given string is null. * @throws UnsupportedEncodingException */ public static String decode(String s, String enc) throws UnsupportedEncodingException { return s == null ? null : URLDecoder.decode(s, enc); } public static String encode(String s, String enc) throws UnsupportedEncodingException { return URLEncoder.encode((s == null ? "" : s), enc); } /** * * 判断网络状态是否可用 * * @return true: 网络可用 ; false: 网络不可用 */ public static boolean isNetworkConnected(Activity activity) { ConnectivityManager conManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = conManager.getActiveNetworkInfo(); if (networkInfo != null) { // 这个判断一定要,要不然会出错 return networkInfo.isAvailable(); } return false; }}
详细解决方案
Android 网络操作(下传上载等)
热度:26 发布时间:2016-05-01 18:46:37.0
相关解决方案
- android 读取byte[]中的元素解决方案
- android 标题栏兑现方式
- android 中Activity向BroadcastReceiver发送数据,该怎么解决
- Android 4.0 为什么模拟器老是提示小弟我谷歌拼音输入法已停止
- android:getSharedPreferences() 这是哪个类的方法解决思路
- android 怎么判断一个程序是否联网
- android 大量数据按周分组,该如何解决
- android RadioButton如何设置默认选中
- ksoap2-android-这个包,连接webService怎么设置超时
- android 怎么重新设置锚点
- android UI界面设计解决方案
- android 图片对象获取的有关问题
- android 怎么调用淘宝支付宝接口
- Android 沿袭InputMethodService自定义输入法
- android 关于服务连接的疑义
- android 两个activity如何通信
- android 怎么实现对view的放大和缩小
- android 教程解决方法
- android ID,该如何处理
- 准备复习2-3个月,看java+android,请问有经验者,怎么看效果最好》
- android UI线程与AsyncTask的有关问题
- android(java)中的java.net能不能和c#的system.net.sockets进行tcp通信,该如何解决
- android ListView 中的onItemClick Intent 没法跳转
- android(java) 中文乱码的有关问题
- c#c++,android,ios(iphone),php,java视屏课程 散分
- android Post文件到ASP.NET的有关问题,能收到参数收不到文件
- RIM 替 Android 开发者提供免费的 PlayBook!2月13日前
- android 动态设立控件高度
- Android test project 编译方法
- android -相机使用教程(1)解决方法