java通过java.net.URL发送http请求调用接口
一般在*.html,*.jsp页面中我们通过使用ajax调用接口,这个是我们通常用的。对于这些接口,大都是本公司写的接口供自己调用,所以直接用ajax就可以。但是,如果是多家公司共同开发一个东西,一个功能可能要调多个接口,一两个ajax可以在jsp页面上显示,但是如果多了,就不能写这么多ajax在前端了。这时候需要封装一成一个接口,在接口里面如何调用其他接口呢?这就用到了java.net.URL这个类。
java.net.URL用法如下
BufferedReader in=null; java.net.HttpURLConnection conn=null; String msg = "";// 保存调用http服务后的响应信息 try {
//实例化url java.net.URL url = new java.net.URL(path);
//根据url获取HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
//设置请求的参数 conn.setRequestMethod("POST"); conn.setConnectTimeout(5 * 1000);// 设置连接超时时间为5秒 conn.setReadTimeout(20 * 1000);// 设置读取超时时间为20秒 conn.setDoOutput(true); // 使用 URL 连接进行输出,则将 DoOutput标志设置为 true conn.setDoInput(true); conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); //conn.setRequestProperty("Content-Encoding","gzip"); conn.setRequestProperty("Content-Length", String.valueOf(params.length())); //设置请求内容(长度)长度 OutputStream outStream = conn.getOutputStream(); // 返回写入到此连接的输出流 outStream.write(params.getBytes()); //将参数写入流中 outStream.close();//关闭流 if (conn.getResponseCode() == 200) { // HTTP服务端返回的编码是UTF-8,故必须设置为UTF-8,保持编码统一,否则会出现中文乱码 in = new BufferedReader(new InputStreamReader((InputStream) conn.getInputStream(), "UTF-8")); msg = in.readLine(); } }catch(Exception ex) { ex.printStackTrace(); }finally { if(null!=in) { in.close(); } if(null!=conn) { conn.disconnect(); } } return msg;
HttpUtil工具类
两个注意点:
1.请求头中要加上编码方式及各种需要的头信息
2.参数转换成字节数组时一定要使用getBytes("编码方式");使用getBytes会导致换一个jvm编码默认方式就不一样。
import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; /** * http工具 * */ public final class HttpUtil { /** * 模拟http协议发送get请求 **/ public static String sendGetRequest(String url) { String result = ""; InputStream in = null; HttpURLConnection connection = null; try { URL httpUrl = new URL(url); connection = (HttpURLConnection) httpUrl.openConnection(); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("Charset", "UTF-8"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setRequestMethod("GET"); connection.connect(); if (connection.getResponseCode() == 200) { in = connection.getInputStream(); ByteArrayOutputStream bs = new ByteArrayOutputStream(); int n = 0; byte[] datas = new byte[2048]; while ((n = in.read(datas)) != -1) { bs.write(datas, 0, n); } bs.flush(); result = new String(bs.toByteArray(), "utf-8"); } } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (Exception e) { e.printStackTrace(); } try { connection.disconnect(); } catch (Exception ex) { } } return result; } /** * 模拟http协议发送post请求 **/ public static String sendPostRequest(String url, String param) { InputStream in = null; String result = ""; HttpURLConnection connection = null; try { URL httpUrl = new URL(url); connection = (HttpURLConnection) httpUrl.openConnection(); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("Charset", "UTF-8"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.getOutputStream().write(param.getBytes("utf-8")); connection.getOutputStream().flush(); if (connection.getResponseCode() == 200) { in = connection.getInputStream(); ByteArrayOutputStream bs = new ByteArrayOutputStream(); int n = 0; byte[] datas = new byte[2048]; while ((n = in.read(datas)) != -1) { bs.write(datas, 0, n); } bs.flush(); result = new String(bs.toByteArray(), "utf-8"); } } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } try { connection.disconnect(); } catch (Exception ex) { } } return result; } /** * 普通post文件上传 */ public static String upLoadAttachment(String url, String fileName, File file) { String result = null; HttpURLConnection connection = null; BufferedReader reader = null; try { URL httpUrl = new URL(url); connection = (HttpURLConnection) httpUrl.openConnection(); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("Charset", "UTF-8"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setRequestMethod("POST"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); String bound = "----------" + System.currentTimeMillis(); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + bound); StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(bound); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"" + fileName + "\";filename=\"" + file.getName() + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] data = sb.toString().getBytes("utf-8"); OutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(data); DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); byte[] foot = ("\r\n--" + bound + "--\r\n").getBytes("utf-8"); // 定义最后数据分隔线 out.write(foot); out.flush(); out.close(); InputStream inn = connection.getInputStream(); ByteArrayOutputStream bs = new ByteArrayOutputStream(); int n = 0; byte[] datas = new byte[2048]; while ((n = inn.read(datas)) != -1) { bs.write(datas, 0, n); } bs.flush(); result = new String(bs.toByteArray(), "utf-8"); return result; } catch (Exception ex) { ex.printStackTrace(); } finally { try { connection.disconnect(); } catch (Exception ex) { } } return null; } /** * post文件上传 - 使用InputStream输入流(例如MultipartFile从前端获取文件后转发给其他的服务器) */ public static String upLoadAttachment(String url,String keyName, String fileName, InputStream fins) { String result = null; HttpURLConnection connection = null; BufferedReader reader = null; try { URL httpUrl = new URL(url); connection = (HttpURLConnection) httpUrl.openConnection(); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("Charset", "UTF-8"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setRequestMethod("POST"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); String bound = "----------" + System.currentTimeMillis(); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + bound); StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(bound); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"" + keyName + "\";filename=\"" + fileName + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] data = sb.toString().getBytes("utf-8"); OutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(data); DataInputStream in = new DataInputStream(fins); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); byte[] foot = ("\r\n--" + bound + "--\r\n").getBytes("utf-8"); // 定义最后数据分隔线 out.write(foot); out.flush(); out.close(); InputStream inn = connection.getInputStream(); ByteArrayOutputStream bs = new ByteArrayOutputStream(); int n = 0; byte[] datas = new byte[2048]; while ((n = inn.read(datas)) != -1) { bs.write(datas, 0, n); } bs.flush(); result = new String(bs.toByteArray(), "utf-8"); return result; } catch (Exception ex) { ex.printStackTrace(); } finally { try { connection.disconnect(); } catch (Exception ex) { } } return null; } }
如果这篇文章对你有用,可以关注本人微信公众号获取更多ヽ(^ω^)ノ ~