先来个传统的,不过这个里面有些类已经标明 deprecated,所以之后还有更好的方法,起码没有被标明 deprecated的类和方法。

前两个方法是有deprecated的情况。后面用HttpURLConnection 对象的是没有deprecated的。最后还有个设置代理的方法。就是设置代理了,HttpUrlConnection对象也可以通过 usingProxy 方法判断是否使用代理了。

/**
* 工具包
*/
package utils; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import org.apache.http.HttpResponse;
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.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils; import android.net.Uri;
import android.util.Log;
import android.view.ViewDebug.FlagToString; /**
* 和Htttp相关的类
*
* @author Administrator
*
*/
public class HttpUtils {
private static final int HTTP_STATUS_OK = 200; /**
* 通过post协议发送请求,并获取返回的响应结果
*
* @param url
* 请求url
* @param params
* post传递的参数
* @param encoding
* 编码格式
* @return 返回服务器响应结果
* @throws HttpException
*/
public static String sendPostMethod(String url, Map<String, Object> params,
String encoding) throws Exception {
String result = ""; HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url); // 封装表单
if (null != params && !params.isEmpty()) {
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
for (Map.Entry<String, Object> entry : params.entrySet()) {
String name = entry.getKey();
String value = entry.getValue().toString();
BasicNameValuePair pair = new BasicNameValuePair(name, value);
parameters.add(pair);
} try {
// 此处为了避免中文乱码,保险起见要加上编码格式
UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(
parameters, encoding);
post.setEntity(encodedFormEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.d("shang", "UnsupportedEncodingException");
}
}
try {
HttpResponse response = client.execute(post);
if (HTTP_STATUS_OK == response.getStatusLine().getStatusCode()) {
// 获取服务器请求的返回结果,注意此处为了保险要加上编码格式
result = EntityUtils.toString(response.getEntity(), encoding);
} else {
throw new Exception("Invalide response from API"
+ response.toString());
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
} /**
* 通过get方式发送请求,并返回响应结果
*
* @param url
* 请求地址
* @param params
* 参数列表,例如name=小明&age=8里面的中文要经过Uri.encode编码
* @param encoding
* 编码格式
* @return 服务器响应结果
* @throws Exception
*/
public static String sendGetMethod(String url, String params,
String encoding) throws Exception {
String result = "";
url += ((-1 == url.indexOf("?")) ? "?" : "&") + params; HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
get.setHeader("charset", encoding); try {
HttpResponse response = client.execute(get);
if (HTTP_STATUS_OK == response.getStatusLine().getStatusCode()) {
result = EntityUtils.toString(response.getEntity(), encoding);
} else {
throw new Exception("Invalide response from Api!"
+ response.toString());
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
} /**
* 通过URLConnect的方式发送post请求,并返回响应结果
*
* @param url
* 请求地址
* @param params
* 参数列表,例如name=小明&age=8里面的中文要经过Uri.encode编码
* @param encoding
* 编码格式
* @return 服务器响应结果
*/
public static String sendPostMethod(String url, String params,
String encoding) {
String result = "";
PrintWriter out = null;
BufferedReader in = null; try {
URL realUrl = new URL(url);
// 打开url连接
HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
// 5秒后超时
conn.setConnectTimeout(5000); // 设置通用的属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1"); // post请求必须有下面两行
conn.setDoOutput(true);
conn.setDoInput(true);
// post请求不应该使用cache
conn.setUseCaches(false); //显式地设置为POST,默认为GET
conn.setRequestMethod("POST");
// 获取Urlconnection对象的输出流,调用conn.getOutputStream的时候就会设置为POST方法
out = new PrintWriter(conn.getOutputStream());
// 发送参数
out.print(params);
// flush输出流的缓冲,这样参数才能发送出去
out.flush(); // 读取流里的内容,注意编码问题
in = new BufferedReader(new InputStreamReader(
conn.getInputStream(), encoding)); String line = "";
while (null != (line = in.readLine())) {
result += line;
} } catch (IOException e) {
System.out.println("Send post Exection!");
e.printStackTrace();
} finally {
// 关闭流
try {
if (null != out) {
out.close();
}
if (null != in) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} return result;
} /**
* 采用URLConnection的方式发送get请求
*
* @param url
* 请求地址
* @param params
* 参数列表,例如name=小明&age=8里面的中文要经过Uri.encode编码
* @param encoding
* 编码格式
* @return 服务器响应结果
*/
public static String sendGetRequest(String url, String params,
String encoding) {
String result = "";
BufferedReader in = null; // 连接上参数
url += ((-1 == url.indexOf("?")) ? "?" : "&") + params; try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection(); // 通用设置
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (comptibal; MSIE 6.0; Windows NT 5.1;SV1 )"); // 不使用缓存
conn.setUseCaches(false); // 建立链接
conn.connect(); // 获取所有头字段
Map<String, List<String>> headers = conn.getHeaderFields();
for (String key : headers.keySet()) {
List<String> value = headers.get(key);
Log.d("shang", "key=>" + value.toString());
} in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while (null != (line = in.readLine())) {
result += line;
}
} catch (IOException e) {
Log.d("shang", "Send get Exception!");
e.printStackTrace();
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
Log.d("shang", "BufferReader close Exception!");
e.printStackTrace();
}
}
} return result;
} /**
* 设置代理
*
* @param ip
* 代理ip
* @param port
* 代理端口号
*/
public static void setProxy(String ip, String port) {
// 如果不设置,只要代理IP和代理端口正确,此项不设置也可以
System.getProperties().setProperty("http.proxyHost", ip);
System.getProperties().setProperty("http.proxyPort", port);
}
}

Java 代码实现Http 的GET和POST 请求的更多相关文章

  1. 通过java代码HttpRequestUtil(服务器端)发送HTTP请求并解析

    关键代码:String jsonStr = HttpRequestUtil.sendGet(config.getAddress() + config.getPorts() + config.getFi ...

  2. 对一致性Hash算法,Java代码实现的深入研究

    一致性Hash算法 关于一致性Hash算法,在我之前的博文中已经有多次提到了,MemCache超详细解读一文中"一致性Hash算法"部分,对于为什么要使用一致性Hash算法.一致性 ...

  3. 怎样编写高质量的java代码

    代码质量概述     怎样辨别一个项目代码写得好还是坏?优秀的代码和腐化的代码区别在哪里?怎么让自己写的代码既漂亮又有生命力?接下来将对代码质量的问题进行一些粗略的介绍.也请有过代码质量相关经验的朋友 ...

  4. 数据结构笔记--二叉查找树概述以及java代码实现

    一些概念: 二叉查找树的重要性质:对于树中的每一个节点X,它的左子树任一节点的值均小于X,右子树上任意节点的值均大于X. 二叉查找树是java的TreeSet和TreeMap类实现的基础. 由于树的递 ...

  5. java代码的初始化过程研究

        刚刚在ITeye上看到一篇关于java代码初始化的文章,看到代码我试着推理了下结果,虽然是大学时代学的知识了,没想到还能做对.(看来自己大学时掌握的基础还算不错,(*^__^*) 嘻嘻……)但 ...

  6. JDBC——Java代码与数据库链接的桥梁

    常用数据库的驱动程序及JDBC URL: Oracle数据库: 驱动程序包名:ojdbc14.jar 驱动类的名字:oracle.jdbc.driver.OracleDriver JDBC URL:j ...

  7. 利用Java代码在某些时刻创建Spring上下文

    上一篇中,描述了如何使用Spring隐式的创建bean,但当我们需要引进第三方类库添加到我们的逻辑上时,@Conponent与@Autowired是无法添加到类上的,这时,自动装配便不适用了,我们需要 ...

  8. lombok 简化java代码注解

    lombok 简化java代码注解 安装lombok插件 以intellij ide为例 File-->Setting-->Plugins-->搜索"lombok plug ...

  9. 远程debug调试java代码

    远程debug调试java代码 日常环境和预发环境遇到问题时,可以用远程调试的方法本地打断点,在本地调试.生产环境由于网络隔离和系统稳定性考虑,不能进行远程代码调试. 整体过程是通过修改远程服务JAV ...

随机推荐

  1. Linux下编译C++程序遇到错误:undefined reference to `*::*

    “undefined reference to”的意思是,该函数未定义. 如果使用的是g++,有以下检查方案: 如果提示未定义的函数是某个库的函数.检查库是否已经安装,并在编译命令中采用-l和-L参数 ...

  2. Python删除列表中元素

    Python中列表(list)是很常用的数据结构,删除列表中的元素有几种方法 列表的remove方法 lst = [1, 1, 3, 4] lst.remove(1) # lst->[1, 3, ...

  3. jquery 查找元素

    /************ 查找父元素 *************/ //closest()方法 $("#mytd1").bind("click",functi ...

  4. [未解决]Exception in thread "main" java.lang.IllegalArgumentException: offset (0) + length (8) exceed the capacity of the array: 6

    调用这个方法 是报错,未解决 binfo.setTradeAmount(Double.parseDouble(new String(result.getValue(Bytes.toBytes(fami ...

  5. http://jadethao.iteye.com/blog/1926525

    http://jadethao.iteye.com/blog/1926525 ————————————————————————————————————————————————————————————— ...

  6. 关于Unity中调试C#的方法

    1.断点输出语句 在感觉有问题的地方的上下文写一些输出语句,如果控制台只有输出上文,没有输出下文,那么可以知道,上下文之间的语句有问题,因为下文没执行到,没有输出语句. Debug.Log(" ...

  7. TensorFlow基础笔记(1) 数据读取与保存

    https://zhuanlan.zhihu.com/p/27238630 WholeFileReader # 我们用一个具体的例子感受tensorflow中的数据读取.如图, # 假设我们在当前文件 ...

  8. AWT是Java最早出现的图形界面,但很快就被Swing所取代

    AWT是Java最早出现的图形界面,但很快就被Swing所取代. Swing才是一种真正的图形开发. AWT在不同平台所出现的界面可能有所不同:因为每个OS都有自己的UI组件库,java调用不同系统的 ...

  9. javascript年月日日期筛选控件

    来源:http://www.sucaihuo.com/js/1158.html demo:http://www.sucaihuo.com/jquery/11/1158/demo/

  10. Ubuntu Mysql 安装

    下载 http://dev.mysql.com/downloads/mysql/ 选择 Linux- Generic 选择版本 wget http://cdn.mysql.com/Downloads/ ...