`
四眼蛤蟆
  • 浏览: 97731 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Http——Get和Post

    博客分类:
  • Java
 
阅读更多

public class Http {
	/**
	 * Http Get fashion
	 * 
	 * @param url
	 * @return
	 */
	public static String doGet(String url) {
		String data = null;
		// 初始化Http请求对象
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResponse = null;
		try {
			// 执行请求
			try {
				httpResponse = httpClient.execute(httpGet);
			} catch (Exception e) {
				e.printStackTrace();
			}
			// 请求到的数据
			HttpEntity httpEntity = httpResponse.getEntity();

			if (httpEntity != null) {
				// 得到返回数据:流数据
				InputStream inputStream = httpEntity.getContent();
				data = convertStreamToString(inputStream);
				// 缓存请求结果,目前不实现
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.d("jsonResult", data);
		return data;
	}

	/**
	 * Http post fashion
	 * 
	 * @param url
	 *            :请求地址
	 * @param postData
	 *            : 请求数据
	 * @return
	 */
	public static String doPost(String url, Map<String, String> postData) {
		String data = null;
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		HttpResponse httpResponse = null;

		// 整理数据
		ArrayList<BasicNameValuePair> clearUpData = new ArrayList<BasicNameValuePair>();
		if (postData != null) {
			Set<String> keys = postData.keySet();
			for (Iterator<String> i = keys.iterator(); i.hasNext();) {
				String key = (String) i.next();
				clearUpData.add(new BasicNameValuePair(key, (String) postData
						.get(key)));
			}
		}
		try {
			// utf-8编码
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(clearUpData,
					"utf-8");
			// 设置最终数据
			httpPost.setEntity(entity);
			// 执行
			httpResponse = httpClient.execute(httpPost);
			// 请求到的数据
			HttpEntity httpEntity = httpResponse.getEntity();
			if (httpEntity != null) {
				// 得到返回数据:流数据
				InputStream inputStream = httpEntity.getContent();
				data = convertStreamToString(inputStream);
				// 缓存请求结果,目前不实现
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.d("jsonResult", data);
		return data;
	}

	/**
	 * 将流转换为字符串
	 * 
	 * @param is
	 * @return
	 */
	private static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return sb.toString();
	}
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics