Android 请求

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;

import com.google.gson.Gson;

/**
 * json字符串 和对象互换 工具类
 * 依赖Gson包
 * @see com.google.gson.Gson
 * @author devil
 *
 */
public class JsonUtil {

	/**
	 * 将json字符串转换成对象
	 *
	 * @param json
	 * @param type
	 * @return
	 */
	public static <T> T parse(String json, Class<T> type) {
		Gson gson = new Gson();
		T t = null ;
		try {
			 t = gson.fromJson(json, type) ;
		} catch (Exception e) {
			e.printStackTrace() ;
			return null ;
		}

		return t;
	}

	/**
	 * 将json转成数组
	 *
	 * @param json
	 * @param type
	 * @return
	 */
	public static <T> T[] parseArr(String json, Class<T[]> type) {
		return parse(json, type);
	}

	/**
	 * 将json转成集合
	 *
	 * @param json
	 * @param type
	 * @return
	 */
	public static <T> ArrayList<T> parseList(String json, Class<T[]> type) {
		return new ArrayList<T>(Arrays.asList(parse(json, type)));
	}

	/**
	 * 将对象转成json字符串
	 *
	 * @param o
	 * @return
	 */
	public static String format(Object o) {
		Gson gson = new Gson();
		return gson.toJson(o);
	}

	/**
	 * 将对象转成json字符串 并使用url编码
	 * @param o
	 * @return
	 */
	public static String formatURLString(Object o)
	{
		try
		{
			return URLEncoder.encode(format(o), "utf-8");
		}catch (Exception e) {
			return null;
		}
	}
}

HttpPost httpPost = new HttpPost(url);
		try {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("username", username));

			httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpConnectionParams.setConnectionTimeout(httpPost.getParams(), 10000);//设置连接超时
			HttpConnectionParams.setSoTimeout(httpPost.getParams(), 10000); //设置请求超时
			HttpResponse httpResponse =httpclient.execute(httpPost);
			if(httpResponse.getStatusLine().getStatusCode()==200){//成功响应了请求

public static String postHttpResponseText(String url, String post) {
		BufferedReader reader = null;
		HttpURLConnection conn = null;
		try {
			URL httpUrl = new URL(url);
			HttpURLConnection httpConn = (HttpURLConnection) httpUrl
					.openConnection(); // //设置连接属性
			httpConn.setDoOutput(true);// 使用URL 连接进行输出
			httpConn.setDoInput(true);// 使用 URL 连接进行输入
			httpConn.setUseCaches(false);// 忽略缓存
			httpConn.setRequestMethod("POST");// 设置URL请求方法
			String requestString = post; // 设置请求属性
			// 获得数据字节数据,请求数据流的编码,必须和下面服务器端处理请求流的编码一致
			byte[] requestStringBytes = requestString.getBytes("UTF-8");
			httpConn.setRequestProperty("Content-length", ""
					+ requestStringBytes.length);
			httpConn.setRequestProperty("Content-Type", "application/json");
			httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
			httpConn.setRequestProperty("Charset", "UTF-8");
			// 建立输出流,并写入数据
			OutputStream outputStream = httpConn.getOutputStream();
			outputStream.write(requestStringBytes);
			outputStream.close(); // 获得响应状态
			int responseCode = httpConn.getResponseCode();
			if (HttpURLConnection.HTTP_OK == responseCode) {// 连接成功 //
															// 当正确响应时处理数据
				StringBuffer buffer = new StringBuffer();
				String readLine = null;
				// 处理响应流,必须与服务器响应流输出的编码一致
				reader = new BufferedReader(new InputStreamReader(
						httpConn.getInputStream(), "UTF-8"));
				while ((readLine = reader.readLine()) != null) {
					//buffer.append(readLine).append("\n");
					buffer.append(readLine);
				}
				reader.close();
				return buffer.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return null;

	}
时间: 2024-08-01 13:21:12

Android 请求的相关文章

Android 请求root权限实现静默安装

这几天在做一个新的功能,需要用到静默安装,所以在网上找了一些静默安装的资料就在这里记录一下吧.其实实现静默安装的原理就是请求Android手机的root权限,通过执行Linux命令来安装APK到手机系统,其实代码不是很多,就在这里列一下吧,以后用的时候可以直接翻出来: 1 public class MyThread extends Thread { 2 private String path; 3 4 public MyThread(String path) { 5 // TODO Auto-g

使用Volley来写一个List列表(Valley可以解决很大一部分android请求server的问题)

先上效果图: 先写一个Volley的请求的类: public void fetchData() { String url = "http://2.novelread.sinaapp.com/framework-sae/index.php"; // String body = ""; // try { // mEntity = new StringEntity(body); // } catch (UnsupportedEncodingException e1) {

android 请求网络异步加载

/** * 封装ProecssDialog对话框 * */ public class LoadDialog extends ProgressDialog { private String title = "进度对话框"; private String message = "加载数据中...."; public LoadDialog(Context context, int theme) { super(context, theme); } /** * 用默认的标题和

Android 请求WebService 并且解析

直接上代码: 写一个Bean,封装数据 package com.mbl.wbsconn; import java.util.List; import java.util.Map; public class BaseBean { protected String usid; protected String pwd; protected String error; protected String msgtp; protected String logonstatus; protected Lis

Android 各大网络请求库的比较及实战,android请求库实战

自己学习android也有一段时间了,在实际开发中,频繁的接触网络请求,而网络请求的方式很多,最常见的那么几个也就那么几个.本篇文章对常见的网络请求库进行一个总结. HttpUrlConnection 最开始学android的时候用的网络请求是HttpUrlConnection,当时很多东西还不知道,但是在android 2.2及以下版本中HttpUrlConnection存在着一些bug,所以建议在android 2.3以后使用HttpUrlConnection,之前使用HttpClient.

Android请求网络共通类——Hi_博客 Android App 开发笔记

今天 ,来分享一下 ,一个博客App的开发过程,以前也没开发过这种类型App 的经验,求大神们轻点喷. 首先我们要创建一个Andriod 项目 因为要从网络请求数据所以我们先来一个请求网络的共通类. 思路: 1.把请求网络的方法放到一个类里面 2.创建一个接口将数据发给Activity 3.Activity 实现接口获得服务器返回的数据 4.解析数据 来我们一先来看第一步 请求网络 在这里请求网络我们用Volley .Volley是Android平台上的网络通信库,能使网络通信更快,更简单,更健

varnish 配置使用 Chrome,iphone,android 请求响应各自的页面

简单拓扑如下 后端服务器上有4个网页文件,每个文件分别如下,每个文件都对应相应的客户端请求 index.html chrome.html admroid.html iphone.html varnish 下载区 http://repo.varnish-cache.org/ 这里使用的软件版本 varnish-3.0.5-1.el6.x86_64.rpm                 提供varnish主程序 varnish-docs-3.0.5-1.el6.x86_64.rpm       

android请求http 关于connection.getResponseCode() 等于-1的问题

直接通过浏览器输入链接请求服务端是正常的, 如果用android端 使用HttpURLConnection请求,  得到的getResponseCode() 会返回-1, 主要问题在于线程, 要单独走一个线程, 不能直接走主线程 解决方法有两种: 一:为该请求单独起一个线程 二:自己写个方法: public static void closeStrictMode() { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(

android请求root权限

应用获取Root权限的原理:让应用的代码执行目录获取最高权限.在Linux中通过chmod 777 [代码执行目录] //请求root权限    public static boolean upgradeRootPermission(String pkgCodePath) {          Process process = null;          DataOutputStream os = null;          Boolean resBoolean;        try {