为何要把参考资料放在前面,主要是方便你们资料阅读。html
简单介绍Java网络编程中的HTTP请求
http://www.jb51.net/article/72651.htmjava
HttpURLConnection用法详解
http://www.cnblogs.com/guodongli/archive/2011/04/05/2005930.html
http://0411.iteye.com/blog/1068297web
关于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网络
一、UserInfo rest服务器类,前一篇文章讲解了如何搭建rest服务
二、HttpTools http工具类,实现了doget与dopost方法
三、TestRest 测试类并发
如下代码已经测试经过。app
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;
}
}
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;
}
}
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);
} }