Java代码发送Http请求
来源:互联网 发布:三毛作品 知乎 编辑:程序博客网 时间:2024/06/07 12:50
最近在项目中要使用Java代码来发送Http请求,在查找资料的过程中收获颇多,故记此文,以备后看。
这里我将报文头,报文体等信息都存储在Map里面传到方法里面来。
使用GET方式向URL发送请求
/** * 获取接口返回的结果(GET). * * @param getUrl 请求接口的url * @param requestParam 请求接口的参数 * @param requestHeader 请求接口的Header * @return 请求接口的返回值 * @throws IOException the io exception */ public static String getGetResponseMess(String getUrl, Map<Object, Object> requestParam,Map<Object, Object> requestHeader) throws IOException { String param = ""; if (requestParam != null) { for (Map.Entry<Object, Object> entry : requestParam.entrySet()) { if ("".equals(param) || param == "") { param = entry.getKey() + "=" +URLEncoder.encode(entry.getValue().toString(), "utf-8"); } else { param = param + "&" + entry.getKey() + "=" +URLEncoder.encode( entry.getValue().toString(), "utf-8"); } } } getUrl=getUrl+"?"+param; URL url = new URL(getUrl); // 将url 以 open方法返回的urlConnection 连接强转为HttpURLConnection连接 (标识一个url所引用的远程对象连接) HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 此时cnnection只是为一个连接对象,待连接中 if (requestHeader != null) { // 设置 Header 信息 for (Map.Entry<Object, Object> entry : requestHeader.entrySet()) { connection.setRequestProperty(entry.getKey().toString(), entry.getValue().toString()); } } connection.connect();//建立连接 // 获取输入流 BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) {// 循环读取流 sb.append(line); } br.close();// 关闭流 connection.disconnect();// 断开连接 return sb.toString(); }
使用POST方式向URL发送请求
/** * 获取接口返回的结果(POST). * * @param postUrl 请求接口的url * @param requestParam 请求接口的参数 * @param requestBodyParam 请求接口的Body * @param requestHeader 请求接口的Header * @return 请求接口的返回值 * @throws IOException the io exception */ public static String getResponseMess(String postUrl, Map<Object, Object> requestParam,Map<Object, Object> requestHeader) throws IOException { URL url = new URL(postUrl); // 将url 以 open方法返回的urlConnection 连接强转为HttpURLConnection连接 (标识一个url所引用的远程对象连接) HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 此时cnnection只是为一个连接对象,待连接中 // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数) connection.setDoOutput(true); // 设置连接输入流为true connection.setDoInput(true); // 设置请求方式为post connection.setRequestMethod("POST"); // post请求缓存设为false connection.setUseCaches(false); // 设置该HttpURLConnection实例是否自动执行重定向 connection.setInstanceFollowRedirects(true); if (requestHeader != null) { // 设置 Header 信息 for (Map.Entry<Object, Object> entry : requestHeader.entrySet()) { connection.setRequestProperty(entry.getKey().toString(), entry.getValue().toString()); } } connection.connect();//建立连接 DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); String param = ""; if (requestParam != null) { for (Map.Entry<Object, Object> entry : requestParam.entrySet()) { if ("".equals(param) || param == "") { param = entry.getKey() + "=" +URLEncoder.encode(entry.getValue().toString(), "utf-8"); } else { param = param + "&" + entry.getKey() + "=" +URLEncoder.encode( entry.getValue().toString(), "utf-8"); } } } outputStream.writeBytes(param); outputStream.flush(); outputStream.close(); // 连接发起请求,处理服务器响应 (从连接获取到输入流并包装为bufferedReader) BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line; StringBuilder sb = new StringBuilder(); // 循环读取流,若不到结尾处 while ((line = bf.readLine()) != null) { sb.append(line).append(System.getProperty("line.separator")); } bf.close(); // 关闭流 connection.disconnect(); // 销毁连接 return sb.toString(); }
考虑一种情况,如果相应的请求参数存放在 Raw 里面呢?
我们可以使用HttpClient这个包。
下载地址http://download.csdn.net/download/zjq_1314520/10026953
下载完成之后,我们在项目中导入相应的Jar包即可!
对应我封装的Java代码如下:
/** * 获取接口返回的结果(Raw版本). * * @param postUrl 请求接口的url * @param requestBodyParam 请求Body里面Raw的值 * @param requestHeader 请求头的值 * @return 接口返回参数 * @throws ClientProtocolException the client protocol exception * @throws IOException the io exception */ public static String getResponseMess(String postUrl, String requestBodyParam, Map<Object, Object> requestHeader) throws ClientProtocolException, IOException { HttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(postUrl); StringEntity postingString = new StringEntity(requestBodyParam);// Raw等里面的数据 post.setEntity(postingString); if (requestHeader != null) { for (Map.Entry<Object, Object> entry : requestHeader.entrySet()) { post.setHeader(entry.getKey().toString(), entry.getValue().toString()); } } HttpResponse response = httpClient.execute(post); String responseMess = EntityUtils.toString(response.getEntity()); return responseMess; }
以上就是有关Java代码发送Http请求的相关内容了。
参考博客:
java中的post请求之raw请求–微信api调用java代码示例
java调用http接口
阅读全文
1 0
- java代码发送http请求
- Java代码发送Http请求
- 使用java代码发送HTTP Post请求
- HTTP JAVA代码发送POST请求
- java代码发送HTTP Post请求
- java 发送http请求
- JAVA发送HTTP请求
- Java发送Http请求
- java 发送http请求
- Java发送http请求
- java发送http请求
- java发送http请求
- java发送http请求
- java发送http请求
- java 发送http请求
- java发送http请求
- java发送http请求
- Java发送HTTP请求
- HTML5标签
- bzoj1754 [Usaco2005 qua]Bull Math
- 创新性组织(笔记)
- java运算符
- vue2.0组件之间的通信
- Java代码发送Http请求
- 41. First Missing Positive
- 经典递归问题回顾——汉诺塔
- 动态创建Lambda表达式实现高级查询
- bzoj1753 [Usaco2005 qua]Who's in the Middle
- input标签相关
- 【题目】八数码难题(BFS)
- Substance Designer 生成高清大尺寸地表混合纹理
- Openmp入门(2)(for + sections)