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 ...
随机推荐
- 11 个最佳 jQuery 模拟滚动条插件 scrollbar
1. Windows:全屏窗口滚动插件 该插件可以很好地实现全屏滚动,每滚动一次即为一屏.比如,用户浏览下一屏幕内容时,只需手动滚动到某一位置,该插件会自动滚动显示下一屏全部内容.对于浏览类似于PP ...
- 【PAT】1091 Acute Stroke(30 分)
1091 Acute Stroke(30 分) One important factor to identify acute stroke (急性脑卒中) is the volume of the s ...
- 【AtCoder】ARC087
C - Good Sequence 题解 用个map愉悦一下就好了 代码 #include <bits/stdc++.h> #define fi first #define se seco ...
- 【AtCoder】ARC101题解
C - Candles 题解 点燃的一定是连续的一段,枚举左端点即可 代码 #include <bits/stdc++.h> #define enter putchar('\n') #de ...
- PHP rabbitmq扩展安装
转载自: https://www.jianshu.com/p/65490900a937 安装rabbitmq的php扩展 1.安装扩展依赖库##### 注意:扩展是C写的,由于C与RabbitMQ通信 ...
- Python3 kmeans 聚类算法
# -*- coding: utf-8 -*- """ Created on Wed Jan 10 19:18:56 2018 @author: markli " ...
- muduo学习笔记(二)Reactor关键结构
目录 muduo学习笔记(二)Reactor关键结构 Reactor简述 什么是Reactor Reactor模型的优缺点 poll简述 poll使用样例 muduo Reactor关键结构 Chan ...
- 整理低版本ie兼容问题的解决方案
CSS hack \9 所有的IE10及之前 * IE7以及IE7以下版本的 _ IE6以及IE6以下版本的 !important 提升样式优先级权重 1.ie6,7 ...
- php7 & lua 压测对比
内存:32G CPU:2个6核 接口数据deflate 压缩后 均不到10k, ==== php7 ==== Concurrency Level: 100 Time taken for tests: ...
- android 项目上传SVN不需要上传的文件
bin,gen 不用提交 因为这两个文件夹是自动生成的.如果提交可能会产生编译异常..settings也是自动生成,也不用提交.