以前做过HttpURLConnection传递参数的例子,这次用流来实现,看下面的这个例子。
工具类:
package com.hljw.health.y100.job;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.hljw.health.y100.pojo.CommunityParametersObject;
import com.hljw.util.DateUtil;
public class HttpClient {
private static String _default_encoding = Charset.defaultCharset().name();
//1.发送请求
public static String getResopnseData(String data,String url) {
try {
HttpURLConnection connection = getURL(url);
return sendRequest(connection, data);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//创建httpconn对象
private static HttpURLConnection getURL(String wsUrl) throws Exception {
URL url = new URL(wsUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestProperty("content-type", "text/html");//参数穿不过去请设置这一条
httpConn.setRequestProperty("Accept-Charset", "utf-8");
httpConn.setRequestMethod("POST");
httpConn.setUseCaches(false);
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
Charset.availableCharsets();
httpConn.setInstanceFollowRedirects(true);
return httpConn;
}
//发送请求参数,并得到服务端的返回信息
private static String sendRequest(HttpURLConnection conn, String data)
throws Exception {
conn.getOutputStream().write(data.getBytes("utf-8"));
conn.getOutputStream().flush();
conn.getOutputStream().close();
return response(conn);
}
private static String response(HttpURLConnection conn) throws Exception {
StringBuffer info = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn
.getInputStream(),"utf-8"));
// BufferedReader reader = new BufferedReader(new
// InputStreamReader(conn.getInputStream()));
// conn.connect();
System.out.println("=============================");
System.out.println("Contents of post request");
System.out.println("=============================");
String line = reader.readLine();
while (line != null) {
info.append(line);
line = reader.readLine();
}
System.out.println("=============================");
System.out.println("Contents of post request ends");
System.out.println("=============================");
reader.close();
String ecod = conn.getContentEncoding();
if (ecod == null) {
ecod = _default_encoding;
}
String resData = new String(java.net.URLDecoder.decode(info.toString(),
"UTF-8").getBytes());// ecod
conn.disconnect();
return resData;
// Object obj = getResult(resData);
}
}
服务端:
服务端是一个servlet用来接收发过来的参数处理业务逻辑,向客户端返回信息
package com.hljw.health.y100.service.pinstitutions;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.hljw.health.plat.service.pinstitutions.PInstitutionsService;
import com.hljw.util.SpringUtil;
import com.hljw.util.StringUtil;
public class PInstitutionsServiceServlet extends HttpServlet{
private PInstitutionsService pInstitutionsService = (PInstitutionsService) SpringUtil.getBean("pInstitutionsService");
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("ok");
System.out.println(pInstitutionsService);
ResultObject res=parseResult(request);//解析参数
System.out.println(res);
callBackPrint("哈哈,好的呢?dd", response);//想客户端打印信息
// pInstitutionsService.getPInstitutionsByOrgCode(institutions_code);
}
/**
* 解析参数、回调的内容
* @param request
* @return
* @throws IOException
*/
private ResultObject parseResult(HttpServletRequest request) throws IOException{
StringBuffer info = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8")); //防止中文乱码
String line = reader.readLine();
while (!StringUtil.isBlank(line)) {
info.append(line);
line = reader.readLine();
}
ResultObject obj = null;
if(info.length()>0){
obj = JSON.parseObject(info.toString(), ResultObject.class);
}
return obj;
}
/**
* 回调打印信息
* @author hjh
* @return
*/
private void callBackPrint(String content,HttpServletResponse response) throws IOException{
/*
* 在调用getWriter之前未设置编码(既调用setContentType或者setCharacterEncoding方法设置编码),
* HttpServletResponse则会返回一个用默认的编码(既ISO-8859-1)编码的PrintWriter实例。这样就会
* 造成中文乱码。而且设置编码时必须在调用getWriter之前设置,不然是无效的。
* */
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
//JSON在传递过程中是普通字符串形式传递的,这里简单拼接一个做测试
out.print(content);
out.flush();
out.close();
}
}
测试类
package com.hljw.health.y100.service.pinstitutions;
import com.alibaba.fastjson.JSON;
import com.hljw.health.y100.job.HttpClient;
public class Test {
public static void main(String[] args) {
System.out.println("rrrr");
ResultObject res=new ResultObject();
res.setStatus("1");
res.setOpear("check中国");
String resStr = HttpClient.getResopnseData(JSON.toJSONString(res),"http://localhost:8080/healthplat/pInstitutions.action");//发送数据,并得到服务端返回的信息
System.out.println("**********"+resStr);
}
}
参数的传递用的json格式的数据,当然你也可以用其他的格式,值得注意的是
1.参数如果在服务端无法接收是因为在发送的方法里面没有设定,这个问题困扰了我很久,因为无论是servlet,还是struts1,struts2,都没有设置这一个,所以自己要设置一下。
httpConn.setRequestProperty("content-type", "text/html");//参数穿不过去请设置这一条
2.无论什么时候中文出现乱码是因为编码不统一,注意以下几个地方。
a.工具类里面发送的时候要设置中文utf-8编码
b.工具类接收服务端回调请求要设置UTF-8编码
c.服务端servlet接收参数流要用utf-8编码
d.服务端servlet想客户端打印字符的时候要设置UTF-8编码。