import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URI; import java.net.URL; import java.net.URLEncoder; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; 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.message.BasicNameValuePair; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; /** * 网络连接辅助类 *项目名称:xxxxxxxx * * @author linchunda * */ public class HttpUtil { private static final String TAG = "HttpUtil"; /** 连接超时 */ private static final int TIME_OUT = 5 * 1000; /** * 发送post请求 * * @param strUrl * 网址路径 * @param map * 请求的参数 * @return 返回请求的结果 */ public static String executePost(String strUrl, Map<String, String> map) { String result = null; BufferedReader reader = null; try { HttpClient client = new DefaultHttpClient(); // HttpPost连接对象 HttpPost request = new HttpPost(); request.setURI(new URI(strUrl)); // 使用NameValuePair来保存要传递的Post参数 List<NameValuePair> postParameters = new ArrayList<NameValuePair>(); if (null != map) { for (Map.Entry<String, String> entry : map.entrySet()) { Log.i(TAG, entry.getKey() + "=>" + entry.getValue()); postParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } // 设置字符集 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity( postParameters, "utf-8"); request.setEntity(formEntity); HttpResponse response = client.execute(request); // HttpStatus.SC_OK表示连接成功 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { Log.i(TAG, "连接成功,连接状态码为:" + response.getStatusLine().getStatusCode()); reader = new BufferedReader(new InputStreamReader(response .getEntity().getContent())); StringBuffer strBuffer = new StringBuffer(""); String line = null; while ((line = reader.readLine()) != null) { strBuffer.append(line); } result = strBuffer.toString(); Log.i(TAG, result); } else { Log.i(TAG, "连接失败,连接状态码为:" + response.getStatusLine().getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); reader = null; } catch (IOException e) { e.printStackTrace(); } } } return result; } /** * 发送post请求 * * @param urlAddress * 请求的路径 * @param map * 请求的参数 * @return 返回请求后的结果 * @throws AccessUrlException */ public static String executeHttpPost(Context context, String urlAddress, Map<String, String> map) throws AccessUrlException, AccessTimeOutException { try { initSSL(); } catch (KeyManagementException e1) { e1.printStackTrace(); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } SharedPreferences sharedPreferences = context.getSharedPreferences( "YinYiTong", Context.MODE_PRIVATE); String result = null; URL url = null; HttpURLConnection connection = null; InputStreamReader in = null; try { url = new URL(urlAddress); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(TIME_OUT); connection.setDoInput(true);// 使用 URL连接进行输入 connection.setDoOutput(true);// 使用 URL连接进行输出 connection.setUseCaches(false);// 忽略缓存 connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Charset", "utf-8"); // session id String sessionId = sharedPreferences.getString("sessionId", ""); if (!StringUtil.isEmpty(sessionId)) { connection.setRequestProperty("Cookie", sessionId); } StringBuilder params = new StringBuilder(); // 设置参数 if (null != map) { for (Map.Entry<String, String> entry : map.entrySet()) { Log.i(TAG, entry.getKey() + "=>" + entry.getValue()); params.append(entry.getKey()); params.append("="); params.append(URLEncoder.encode(entry.getValue(), "utf-8")); params.append("&"); } } if (params.length() > 0) params.deleteCharAt(params.length() - 1); OutputStream outputStream = null; try { outputStream = connection.getOutputStream(); } catch (Exception e) { Log.w(TAG, "访问服务器地址:" + urlAddress + "超时."); throw new AccessTimeOutException("访问服务器地址:" + urlAddress + "超时."); } DataOutputStream dop = new DataOutputStream(outputStream); dop.write(params.toString().getBytes()); dop.flush(); dop.close(); if (connection.getResponseCode() == HttpStatus.SC_OK) { Log.i(TAG, "connection status is 200"); // 获取返回结果 in = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(in); StringBuffer strBuffer = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { strBuffer.append(line); } result = strBuffer.toString(); Log.i(TAG, result); // session id不同,重新设置 String session_value = connection.getHeaderField("Set-Cookie"); if (!StringUtil.isEmpty(session_value)) { String[] sessionIds = session_value.split(";"); Log.i(TAG, "sessionId=" + sessionIds[0]); if (null != sessionIds[0] && !sessionIds[0].equalsIgnoreCase(sessionId)) { Editor editor = sharedPreferences.edit(); editor.putString("sessionId", sessionIds[0]); editor.commit(); } } } else { Log.w(TAG, "访问服务器异常,状态码为:" + connection.getResponseCode()); throw new AccessUrlException("访问服务器异常,状态码为:" + connection.getResponseCode()); } } catch (MalformedURLException e) { Log.e(TAG, "[executeHttpPost]:", e); } catch (ProtocolException e) { Log.e(TAG, "[executeHttpPost]:", e); } catch (UnsupportedEncodingException e) { Log.e(TAG, "[executeHttpPost]:", e); } catch (IOException e) { Log.e(TAG, "[executeHttpPost]:", e); } finally { if (connection != null) { connection.disconnect(); } if (in != null) { try { in.close(); } catch (IOException e) { Log.e(TAG, "[executeHttpPost]InputStreamReader关闭异常:", e); } } } return result; } /** * 接受任何证书,不考虑证书发行者及所在主机情况 * * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public static void initSSL() throws NoSuchAlgorithmException, KeyManagementException { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { // Trust always } public void checkServerTrusted(X509Certificate[] certs, String authType) { // Trust always } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); // Create empty HostnameVerifier HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String arg0, SSLSession arg1) { return true; } }; sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(hv); } /** * 检查网络连接 * * @param context * @return 有可用的接连返回true,否则返回false */ public static boolean hasNetwork(Context context) { ConnectivityManager con = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo workinfo = con.getActiveNetworkInfo(); if (workinfo == null || !workinfo.isAvailable()) { Log.w(TAG, "当前无网络连接......"); return false; } return true; } @SuppressWarnings("serial") public static class AccessUrlException extends Exception { public AccessUrlException() { super(); } public AccessUrlException(String msg) { super(msg); } @Override public String toString() { return super.toString(); } } @SuppressWarnings("serial") public static class AccessTimeOutException extends Exception { public AccessTimeOutException() { super(); } public AccessTimeOutException(String msg) { super(msg); } @Override public String toString() { return super.toString(); } } }
--------- 部分实例
try {
HttpResponse response = client.execute(myget);
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity()
.getContent()));
for (String s = reader.readLine(); s != null; s = reader
.readLine()) {
builder.append(s);
}
JSONObject jsonObject = new JSONObject(builder.toString());
error = jsonObject.getInt("errno");
String errormsg = jsonObject.getString("errmsg");
Log.v("wgp",myget.getURI().toString());
Log.v("wgp", "error=" + error);
Log.v("wgp", "errormsg=" + errormsg);
if (error == 0) {
array = jsonObject.getJSONArray("data");
mFavoriteList = new ArrayList<FavoriteItem>();
FavoriteItem item = null;
String srcType;
for (int i = 0; i < array.length(); i++) {
item = new FavoriteItem();
item.setId(array.getJSONObject(i).getInt("id"));
item.setUserId(array.getJSONObject(i).getInt("userid"));
item.setUsername(array.getJSONObject(i).getString("username"));
item.setType(array.getJSONObject(i).getInt("type"));
item.setCid(array.getJSONObject(i).getInt("cid"));
item.setTitle(array.getJSONObject(i).getString("title"));
item.setUrl(array.getJSONObject(i).getString("url"));
item.setTag(array.getJSONObject(i).getString("tag"));
item.setSrc(array.getJSONObject(i).getString("src"));
item.setCreateDate(array.getJSONObject(i).getString("created"));
item.setModifiedDate(array.getJSONObject(i).getString("modified"));
srcType = array.getJSONObject(i).getString("src_type");
if(srcType != null && srcType.equals("cps")){
item.setSrc_type("industry");
}else{
item.setSrc_type(srcType);
}
mFavoriteList.add(item);
}
if (mFavoriteList.size() == 0) {
handler.sendEmptyMessage(-1);
} else {
handler.sendEmptyMessage(1);//更新主UI
}
}
} catch (Exception e) {
e.printStackTrace();
handler.sendEmptyMessage(-1);
} finally {
}
相关推荐
Android util包中的Base64类,在java工程中使用可以
http请求工具类HttpClientUtil,get,post请求(csdn)————程序
真实的Android Base64的jar。下载既可以使用。在Java项目内亦可以。android-util-0.6.0.jar
使用ping命令完成android实时网络质量检测
HttpClientUtil工具类发送get和post请求,支持http和https,支持发送文件
android-common-util.rar 开发工具
java util帮助类,包括日期工具类、字符串处理工具类、上传工具类、http请求工具类、hibernate工具类、MD5工具类、分页工具类等。 CodeStringUtil.java CreateFileUtil.java DateUtil.java FileCopy.java ...
Android史上最全Util工具类集锦: 1.AppUtil 2.BitmapUtil 3.DataUtil 4.FileUtil 5.MobleInfoUtil 6.NetUtil 7.QRUtils(二维码生成工具) 8.ScreenUtil 9.SDCardUtil 10.StringUtils 吐血总结,希望对大家有用
Android Base64Jar包及Java完整源码 包含:android android.util.Base64 类, BASE64编码、解码算法;包含该类的完整Jar包。 可以直接导入Jar包或者引用类及类中相关方法。 很不错的工具类。
C# Util 实用工具类 ,包含:Json、Net、Time、Compress、Config、Enums、File等等等常用使用工具类
org.springframework.web.client.AsyncRestTemplate org.springframework.web.client.RestTemplate HTTP请求工具类,基于以上两个Rest请求工具模板完成封装HTTP请求,包括同步和异步请求的实现。
java util工具类4java util工具类4java util工具类4java util工具类4ssss
Java语言的Util类详细介绍
httpClientUtil工具类
java util工具类2java util工具类2java util工具类2java util工具类2
Java常用工具类UtilClass,包括StringUtil、FileUtil、ConnectDB、DateUtil、TimeUtil一些可能用到的工具,实现某些特定的功能,,
AndroidUtil Android 开发 工具类 总结
Util --- Android开发工具 gradle依赖 compile 'cn.alien95:util:1.1.3' 使用方法 初始化 >开发中常用的一些方法(如:Log,Toast,SnackBar,getScreenWidth,dip2px等等)。 注意:Log的打印应该在Debug模式下。...
android 民间工具集合,以及java 常用的工具类。。