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. K8s中,tomcat的一部分jvm参数,如何通过env环境变量传递?

    这两天解决的一个需求: 如果用户没有在deployment中设置env参数,则tomcat默认使用1G左右的内存: 如果用户在deployment中提供了jvm参数,则tomcat将这部分的参数,覆盖 ...

  2. Qt QByteArray或者Char转十六进制 QString

    1.QByteArray转十六进制 QByteArray buff = sp->readAll(); qDebug() << buff.toHex() << " ...

  3. 【BZOJ】3456: 城市规划(多项式求ln)

    题解 在我写过分治NTT,多项式求逆之后 我又一次写了多项式求ln 我们定义一个数列的指数型生成函数为 \(\sum_{i = 0}^{n} \frac{A_{i}}{i!} x^{i}\) 然后这个 ...

  4. AIM Tech Round 4 (Div. 1) C - Upgrading Tree 构造 + 树的重心

    C - Upgrading Tree 我发现我构造题好弱啊啊啊. 很明显能想到先找到重心, 然后我们的目标就是把所有点接到重心的儿子上,让重心的儿子子树变成菊花图, 这个先把重心到儿子的边连到 i , ...

  5. Could not resolve com.android.support:appcompat-v7:28.0.0 错误处理

      20181008 总是出现错误 Could not resolve com.android.support:appcompat-v7:28.0.0 1.先是怀疑前些天降级了jdk 1.8 ,所以重 ...

  6. Nutch源码阅读进程5

    看nutch的源码仿佛就是一场谍战片,而构成这精彩绝伦的谍战剧情的就是nutch的每一个从inject->generate->fetch->parse->update的环节,首 ...

  7. android 获取sd卡根目录

    dir:/storage/emulated/0 也就是 sdcard目录 ====== android 获取sd卡根目录 public String getSDPath(){        File ...

  8. span 居中

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha ====== 把span 升级为块级元素,div 的宽度.然后使用定位,添加 text- ...

  9. HDU 3802Ipad,IPhone

    前两块可以看成是不是二次剩余,快速幂计算即可. 后半部分可以看成x1=a+b+2ab,x2=a+b-2ab为特征方程x^2-px-qx=0的两根 然后可以通过韦达定理求出p和q,因此递推式为A(n+2 ...

  10. 【BZOJ-4556】字符串 后缀数组+二分+主席树 / 后缀自动机+线段树合并+二分

    4556: [Tjoi2016&Heoi2016]字符串 Time Limit: 20 Sec  Memory Limit: 128 MBSubmit: 657  Solved: 274[Su ...