您的位置:首页 > 理论基础 > 计算机网络

HttpURLConnection用法详解,包含代码

2016-12-21 00:00 686 查看
摘要: 本文主要参考了一些文章,简单介绍Java网络编程中的HTTP请求,对HttpURLConnection做了编码,试验过,可以用。

一、参考资料

为什么要把参考资料放在前面,主要是方便大家资料阅读。

简单介绍Java网络编程中的HTTP请求 http://www.jb51.net/article/72651.htm
HttpURLConnection用法详解 http://www.cnblogs.com/guodongli/archive/2011/04/05/2005930.html http://0411.iteye.com/blog/1068297

关于setConnectTimeout和setReadTimeout的问题 http://blog.csdn.net/jackson_wen/article/details/51923514
HTTP协议头部与Keep-Alive模式详解 http://blog.csdn.net/charleslei/article/details/50621912
HttpURLConnection与HttpClient 区别、联系、性能对比 http://blog.csdn.net/u011479540/article/details/51918474 http://blog.csdn.net/zhou_wenchong/article/details/51243079 http://www.cnblogs.com/liushuibufu/p/4140913.html http://blog.csdn.net/wszxl492719760/article/details/8522714

其他 http://blog.csdn.net/u012228718/article/details/42028951 http://www.jb51.net/article/73621.htm http://blog.csdn.net/u012228718/article/details/42028951 http://blog.csdn.net/u011192000/article/details/47358933

二、HttpURLConnection用法 代码

1、UserInfo rest服务器类,前一篇文章讲解了如何搭建rest服务
2、HttpTools http工具类,实现了doget与dopost方法
3、TestRest 测试类

以下代码已经测试通过。

UserInfo.java

package com.myrest;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

// 这里@Path定义了类的层次路径。
// 指定了资源类提供服务的URI路径。
@Path("UserInfoService")
public class UserInfo {
// @GET表示方法会处理HTTP GET请求
@GET
// 这里@Path定义了类的层次路径。指定了资源类提供服务的URI路径。
@Path("/name/{i}")
// @Produces定义了资源类方法会生成的媒体类型。
@Produces(MediaType.TEXT_XML)
// @PathParam向@Path定义的表达式注入URI参数值。
public String userName(@PathParam("i") String i) {
// 发现get提交,会帮我们自动解码
System.out.println("传入 name:" + i);
String name = "返回name:" + i;
return name;
}

@POST
@Path("/information/")
public String userAge(String info) throws UnsupportedEncodingException {

// post提交需要我们手动解码,避免中文乱码
String str = URLDecoder.decode(info, "UTF-8");
System.out.println("传入参数: " + info);
System.out.println("解码后参数: " + str);
String value = "返回值:" + str;
return value;
}
}

HttpTools.java

package com.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

public final class HttpTools {
private static final int CONNECT_TIMEOUT = 50000;
private static final int READ_TIMEOUT = 30000;

/**
* 使用get请求方式请求数据,注意get传递中文字符需要用URLEncoder
* @param urlPath 请求数据的URL
* @return 返回字符串
*/
public static String doGet(String urlPath){
String ret=null;

if(urlPath!=null){
HttpURLConnection httpConn = null;
try {
// 建立连接
URL url = new URL(urlPath);
httpConn = (HttpURLConnection) url.openConnection();

// 设置参数
//httpConn.setDoOutput(true); // 需要输出
httpConn.setDoInput(true); // 需要输入
httpConn.setUseCaches(false); // 不允许缓存
httpConn.setRequestMethod("GET"); // 设置POST方式连接

// 设置请求属性
// httpConn.setRequestProperty("Content-Type", "application/x-java-serrialized-object");
//设置请求体的类型是文本类型
httpConn.setRequestProperty("Content-Type", "pplication/x-www-form-urlencoded");
//维持长连接,这里要注意,高并发不知道是否有bug
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("Charset", "UTF-8");

//设置超时
httpConn.setConnectTimeout(CONNECT_TIMEOUT); //连接超时时间
httpConn.setReadTimeout(READ_TIMEOUT); //传递数据的超时时间

// 获得响应状态
int resultCode = httpConn.getResponseCode();
if (HttpURLConnection.HTTP_OK == resultCode) {
InputStream inputStream=httpConn.getInputStream();
//处理返回结果
ret=dealResponseResult(inputStream);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return ret;
}

public static String doPost(String urlPath,Map<String, String> params, String encode){
String ret=null;

byte[] data = getRequestData(params, encode).toString().getBytes();//获得请求体

try {

// 建立连接
URL url = new URL(urlPath);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

// 设置参数
httpConn.setDoOutput(true); // 需要输出
httpConn.setDoInput(true); // 需要输入
httpConn.setUseCaches(false); // 不允许缓存
httpConn.setRequestMethod("POST"); // 设置POST方式连接

// 设置请求属性
// httpConn.setRequestProperty("Content-Type", "application/x-java-serrialized-object");
//设置请求体的类型是文本类型
httpConn.setRequestProperty("Content-Type", "pplication/x-www-form-urlencoded");
//设置请求体的长度,可以不需要
httpConn.setRequestProperty("Content-Length", String.valueOf(data.length));
//维持长连接,这里要注意,高并发不知道是否有bug
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("Charset", encode);

//设置超时
httpConn.setConnectTimeout(CONNECT_TIMEOUT); //连接超时时间
httpConn.setReadTimeout(READ_TIMEOUT); //传递数据的超时时间

// 连接,也可以不用明文connect,使用下面的httpConn.getOutputStream()会自动connect
//httpConn.connect();

// 建立输入流,向指向的URL传入参数
DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
dos.write(data);
dos.flush();
dos.close();

// 获得响应状态
int resultCode = httpConn.getResponseCode();
if (HttpURLConnection.HTTP_OK == resultCode) {
InputStream inputStream=httpConn.getInputStream();
//处理返回结果
ret=dealResponseResult(inputStream);
}

} catch (Exception e) {
e.printStackTrace();
return "err: " + e.getMessage().toString();
}

return ret;

}

/**
* 封装请求体信息
* @param params 请求体 参数
* @param encode 编码格式
* @return 返回封装好的StringBuffer
*/
public static StringBuffer getRequestData(Map<String, String> params, String encode) {
StringBuffer stringBuffer = new StringBuffer(); //存储封装好的请求体信息
try {
for(Map.Entry<String, String> entry : params.entrySet()) {
stringBuffer.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(), encode))
.append("&");
}
stringBuffer.deleteCharAt(stringBuffer.length() - 1); //删除最后的一个"&"
} catch (Exception e) {
e.printStackTrace();
}
return stringBuffer;
}

/**
* 处理服务器返回结果
* @param inputStream 输入流
* @return 返回处理后的String 字符串
*/
public static String dealResponseResult(InputStream inputStream) {
String value = null;

try {
//存储处理结果
StringBuffer sb = new StringBuffer();
String readLine = new String();
BufferedReader responseReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
while ((readLine = responseReader.readLine()) != null) {
sb.append(readLine).append("\n");
}
responseReader.close();
value=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
}

TestRest.java

package com.myrest;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import com.util.HttpTools;

public class TestRest {

public static void main(String[] args) throws IOException {
testGet();
testPost();
}

public static void testGet() throws IOException {
String BASE_URI = "http://localhost:8080/webtest";
String PATH_NAME = "/rest/UserInfoService/name/";
String tmp = "奥特曼1号";
// 汉字必须URL编码,否则报错。这里用URLEncoder编码,rest服务需要用URLDecoder解码
String name = URLEncoder.encode(tmp, "UTF-8");
String urlPath = BASE_URI + PATH_NAME + name;
String ret=HttpTools.doGet(urlPath);

System.out.println(ret);

}

public static void testPost() throws IOException {
String BASE_URI = "http://localhost:8080/webtest";
String PATH_NAME = "/rest/UserInfoService/information/";
String urlPath = BASE_URI + PATH_NAME;
Map<String,String> params=new HashMap<String,String>();
params.put("myParam", "我爱我的祖国!");

String ret =HttpTools.doPost(urlPath, params, "utf-8");

System.out.println(ret);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java http