HttpURLConnection和HttpClient的简单用法
HttpURLConnection的简单用法:先通过一个URL创建一个conn对象,然后就是可以设置get或者是post方法,接着用流来读取响应结果即可
String html = null;
long startTime = System.currentTimeMillis();
try {
URL url = new URL("http://www.baidu.com/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000);
if (conn.getResponseCode() == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) { html += line;
}
/*
//第二种方法
InputStream is = conn.getInputStream();
byte []buffer = new byte[is.available()];
is.read();
String result = new String(buffer);*/
} } catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
HttpClient的简单用法:
/**
* @param url
* @return 1.页面源码;2.TimeOut;3.没正确响应,返回null
*/
public String doHttpGet(String url) {
String result = null;
//通过url来创建httpGet对象
HttpGet httpGet = new HttpGet(url);
httpClient = new DefaultHttpClient();
// 请求超时
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
// 读取超时
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,TIME_OUT);
try {
httpResponse = httpClient.execute(httpGet);
// 判断响应的状态码,200表示成功响应了请求
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 得到结果集
result = EntityUtils.toString(httpResponse.getEntity(),"GB2312");
// result = new String(result.getBytes(),"utf-8");
//System.out.println(result);
} else {
System.err.println("未得到正确的响应,响应吗:"+ httpResponse.getStatusLine().getStatusCode());
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
return "TimeOut";
}
return result;
} /**
* @param url
* @param paramsList
* @return 1.页面源码;2.TimeOut;3.没有响应,返回null
*/
public String doHttpPost(String url, List<NameValuePair> paramsList) {
String result = null;
// 根据url创建HttpPost实例
HttpPost httpPost = new HttpPost(url);
httpClient = new DefaultHttpClient();
// 请求超时
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
// 读取超时
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,TIME_OUT);
try {
// 设置HttpPost请求参数必须用NameValuePair对象
httpPost.setEntity(new UrlEncodedFormEntity(paramsList, HTTP.UTF_8));
// 发送post请求
httpResponse = httpClient.execute(httpPost);
// 判断响应的状态码,200表示成功响应了请求
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(httpResponse.getEntity());
//System.out.println(result);
} else {
System.err.println("未得到正确的响应,响应吗:"+ httpResponse.getStatusLine().getStatusCode());
}
} catch (UnsupportedEncodingException e) {
System.out.println("UnsupportedEncodingException");
} catch (ParseException e) {
System.out.println("ParseException");
} catch (IOException e) {
return "TimeOut";
}
return result;
}
工具类NetManager:
package com.kale.mycmcc.net; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils; public class NetManager {
public static int TIME_OUT = 4 * 1000; private HttpResponse httpResponse = null;
private HttpClient httpClient; /**
* @param url
* @return 1.页面源码;2.TimeOut;3.没正确响应,返回null
*/
public String doHttpGet(String url) {
String result = null;
//通过url来创建httpGet对象
HttpGet httpGet = new HttpGet(url);
httpClient = new DefaultHttpClient();
// 请求超时
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
// 读取超时
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,TIME_OUT);
try {
httpResponse = httpClient.execute(httpGet);
// 判断响应的状态码,200表示成功响应了请求
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 得到结果集
result = EntityUtils.toString(httpResponse.getEntity(),"GB2312");
// result = new String(result.getBytes(),"utf-8");
//System.out.println(result);
} else {
System.err.println("未得到正确的响应,响应吗:"+ httpResponse.getStatusLine().getStatusCode());
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
return "TimeOut";
}
return result;
} /**
* @param url
* @param paramsList
* @return 1.页面源码;2.TimeOut;3.没有响应,返回null
*/
public String doHttpPost(String url, List<NameValuePair> paramsList) {
String result = null;
// 根据url创建HttpPost实例
HttpPost httpPost = new HttpPost(url);
httpClient = new DefaultHttpClient();
// 请求超时
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
// 读取超时
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,TIME_OUT);
try {
// 设置HttpPost请求参数必须用NameValuePair对象
httpPost.setEntity(new UrlEncodedFormEntity(paramsList, HTTP.UTF_8));
// 发送post请求
httpResponse = httpClient.execute(httpPost);
// 判断响应的状态码,200表示成功响应了请求
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(httpResponse.getEntity());
//System.out.println(result);
} else {
System.err.println("未得到正确的响应,响应吗:"+ httpResponse.getStatusLine().getStatusCode());
}
} catch (UnsupportedEncodingException e) {
System.out.println("UnsupportedEncodingException");
} catch (ParseException e) {
System.out.println("ParseException");
} catch (IOException e) {
return "TimeOut";
}
return result;
} /* *//**
* 使用正则表达式过滤HTML标记
*//*
private String filterHtml(String source) {
if (null == source) {
return "";
}
return source.replaceAll("</?[^>]+>", "").trim();
} private void showToast(Context mContext, String message, int flag) {
Looper.prepare();
Toast.makeText(mContext, message, flag).show();
Looper.loop();
}*/ }
HttpURLConnection和HttpClient的简单用法的更多相关文章
- Android 中HttpURLConnection与HttpClient的简单使用
1:HttpHelper.java public class HttpHelper { //1:标准的Java接口 public static String getStringFromNet1(Str ...
- android 网络编程之HttpURLConnection与HttpClient使用与封装
1.写在前面 大部分andriod应用需要与服务器进行数据交互,HTTP.FTP.SMTP或者是直接基于SOCKET编程都可以进行数据交互,但是HTTP必然是使用最广泛的协议. 本文并 ...
- HttpURLConnection和HttpClient的区别2(转)
1.HttpClient比HttpURLConnection功能更强大,但是做java建议用前者,安卓建议用后者 2.这两者都支持HTTPS,streaming 上传与下载,配置超时时间,IPv6, ...
- Android HttpURLConnection And HttpClient
Google的工程师的一个博客写到: HttpURLConnection和HttpClient Volley HTTP请求时:在Android 2.3及以上版本,使用的是HttpURLConnecti ...
- 转-Android联网 — HttpURLConnection和HttpClient选择哪个好?
http://www.ituring.com.cn/article/199619?utm_source=tuicool 在Android开发中,访问网络我们是选择HttpURLConnection还是 ...
- [转]Android访问网络,使用HttpURLConnection还是HttpClient
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/12452307 最近在研究Volley框架的源码,发现它在HTTP请求的使用上比较有 ...
- HttpURLConnection与HttpClient浅析
转自:https://blog.csdn.net/u012838207/article/details/82867701 HttpURLConnection与HttpClient浅析 1. GET请求 ...
- HttpURLConnection与HttpClient随笔
目前在工作中遇到的需要各种对接接口的工作,需要用到HTTP的知识,工作完成后想要做一些笔记,本来知识打算把自己写的代码粘贴上来就好了,但是偶然发现一篇博文对这些知识的总结非常到位,自认无法写的这么好, ...
- HttpURLConnection与HttpClient浅析---转
HttpURLConnection与HttpClient浅析 1. GET请求与POST请求 HTTP协议是现在Internet上使用得最多.最重要的协议了,越来越多的Java应用程序需要直接通过HT ...
随机推荐
- IScroll5安卓重复点击兼容问题处理
最近在做移动web开发,使用IScroll 5 的时候出现了设备之间兼容的问题: 情景如下: Android手机:点击滚动区间内的选项时出现点击时间重叠(类似事件冒泡的行为)问题 Apple手机:木有 ...
- 兼容到ie10的js文件导出、下载到本地
话不多说,上代码: try { let reader = new FileReader(); let blob = new Blob([res.data], { type: 'application/ ...
- 电子邮件-TCP
参考下图,由于电子邮件是最早应用于网络上的服务,而早期网络的不可靠性,才设计了TCP协议,而邮件必须要保证正确传输,而非高速,所以早期的电子邮件协议 全是基于TCP的,一直持续到现在.
- 基于ETL技术的数字化校园共享数据中心设计
摘要:数据的抽取.转换与加载(ETL)是数据整合的核心过程.在分析高校信息化建设现状基础上,以建立数字化校园.整合数据资源.实现数据共享为目标,提出以ETL为基础建立共享数据中心实现数据整合的方案.介 ...
- Java中实现多线程的两种方式之间的区别
Java提供了线程类Thread来创建多线程的程序.其实,创建线程与创建普通的类的对象的操作是一样的,而线程就是Thread类或其子类的实例对象.每个Thread对象描述了一个单独的线程.要产生一个线 ...
- 5969 [AK]刻录光盘
题目描述 Description • 在FJOI2010夏令营快要结束的时候,很多营员提出来要把整个夏令营期间的资料刻录成一张光盘给大家,以便大家回去后继续学习.组委会觉得这个主意不错!可是组委会一时 ...
- Asyncio中Lock部分的翻译
Asyncio中Lock部分的翻译 Locks class asyncio.Lock(*, loop=None) 原始锁的对象. 这个基础的锁是一个同步化的组件,当它上锁的时候就不属于典型的协程了(译 ...
- [java] 虚拟机(JVM)底层结构详解[转]
本文来自:曹胜欢博客专栏.转载请注明出处:http://blog.csdn.net/csh624366188 在以前的博客里面,我们介绍了在java领域中大部分的知识点,从最基础的java最基本语法到 ...
- Codeforces Round #272 (Div. 2) E. Dreamoon and Strings 动态规划
E. Dreamoon and Strings 题目连接: http://www.codeforces.com/contest/476/problem/E Description Dreamoon h ...
- hdu 5784 How Many Triangles 计算几何,平面有多少个锐角三角形
How Many Triangles 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5784 Description Alice has n poin ...