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的简单用法的更多相关文章

  1. Android 中HttpURLConnection与HttpClient的简单使用

    1:HttpHelper.java public class HttpHelper { //1:标准的Java接口 public static String getStringFromNet1(Str ...

  2. android 网络编程之HttpURLConnection与HttpClient使用与封装

    1.写在前面     大部分andriod应用需要与服务器进行数据交互,HTTP.FTP.SMTP或者是直接基于SOCKET编程都可以进行数据交互,但是HTTP必然是使用最广泛的协议.     本文并 ...

  3. HttpURLConnection和HttpClient的区别2(转)

    1.HttpClient比HttpURLConnection功能更强大,但是做java建议用前者,安卓建议用后者 2.这两者都支持HTTPS,streaming 上传与下载,配置超时时间,IPv6,  ...

  4. Android HttpURLConnection And HttpClient

    Google的工程师的一个博客写到: HttpURLConnection和HttpClient Volley HTTP请求时:在Android 2.3及以上版本,使用的是HttpURLConnecti ...

  5. 转-Android联网 — HttpURLConnection和HttpClient选择哪个好?

    http://www.ituring.com.cn/article/199619?utm_source=tuicool 在Android开发中,访问网络我们是选择HttpURLConnection还是 ...

  6. [转]Android访问网络,使用HttpURLConnection还是HttpClient

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/12452307 最近在研究Volley框架的源码,发现它在HTTP请求的使用上比较有 ...

  7. HttpURLConnection与HttpClient浅析

    转自:https://blog.csdn.net/u012838207/article/details/82867701 HttpURLConnection与HttpClient浅析 1. GET请求 ...

  8. HttpURLConnection与HttpClient随笔

    目前在工作中遇到的需要各种对接接口的工作,需要用到HTTP的知识,工作完成后想要做一些笔记,本来知识打算把自己写的代码粘贴上来就好了,但是偶然发现一篇博文对这些知识的总结非常到位,自认无法写的这么好, ...

  9. HttpURLConnection与HttpClient浅析---转

    HttpURLConnection与HttpClient浅析 1. GET请求与POST请求 HTTP协议是现在Internet上使用得最多.最重要的协议了,越来越多的Java应用程序需要直接通过HT ...

随机推荐

  1. SpringMVC介绍及参数绑定

    本节内容: SpringMVC介绍 入门程序 SpringMVC架构 SpringMVC整合MyBatis 参数绑定 SpringMVC和Struts2的区别 一.SpringMVC介绍 1. 什么是 ...

  2. linux convert mp3 to wav and opus to wav

    link :  https://www.cyberciti.biz/faq/convert-mp3-files-to-wav-files-in-linux/ Install mpg321 or mpg ...

  3. 全局查询文件linux

    在工作中,可能突然需要找到某个文件,这个又不知道,需要全局查询一下. 下面是命令行: find / -name "*.log" | xargs grep "elk&quo ...

  4. HTML5 标签语法变化和使用概念

    1.H5与H4的区别 概念的变化: H5更注重内容与结构,不再只专注于表现. 声明与标签: 新的声明背简化: <!DOCTYPE html> <meta charset=utf-8& ...

  5. H5的简介

    1.H5的诞生 2.介绍 HTML5 将成为 HTML.XHTML 以及 HTML DOM 的新标准. HTML5 是 W3C 与 WHATWG 合作的结果. WHATWG 致力于 web 表单和应用 ...

  6. 介绍activity文档翻译

    原文链接:https://developer.android.google.cn/guide/components/activities/intro-activitiesSS 一, 对activit的 ...

  7. UI自动化测试(一)简介及Selenium工具的介绍和环境搭建

    自动化测试简介 1.1何为自动化测试? 是把以人为驱动的测试转化为机器执行的一种过程,它是一种以程序测试程序的过程.换言之,就是以程序实现的方式来代替手工测试. 1.2自动化测试分类 分为功能自动化测 ...

  8. 使用systemtap调试工具分析MySQL的性能

    [工具] SystemTap是Linux下的动态跟踪工具,可以方便的监控.跟踪运行中的程序或Linux内核操作,我们通过写SystemTap脚本(与C语言类似),编译为内核模块,然后加载到内核中运行, ...

  9. BZOJ.4571.[SCOI2016]美味(主席树 贪心)

    题目链接 要求 \(b\ xor\ (a_j+x)\) 最大,应让 \(a_j+x\) 的最高位尽可能与b相反.带个减法Trie树好像很难做?反正我不会. 从最高位开始,如果这位b是0/1,判断是否存 ...

  10. poj 3071 概率dp

    转自:cxlove 题目:有2^n个队,相邻的两两打淘汰赛,,求最后哪个队夺冠的概率最大 dp[i][j]表示第i轮的时候,第j去支队伍赢的概率. 那么dp[i][j]的前提就是i-1轮的时候,j是赢 ...