场景:工程师A写了一个基于HTTP的接口(http://127.0.1.2:8080/test/url?param=12&test=asdf&test)这个接口会返回Y,或者N
工程师B现在调用这个接口的方法,见代码!
我们来使用JDK的UR类,和HttpURLConnection
InputStreamReader,BufferedReader,来解决该问题。
package com.cplatform.movie.back.test; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class HttpURLConnectionTest { public static final String GET_URL = "http://112.4.27.9/mall-back/if_user/store_list?storeId=32"; public static final String POST_URL = "http://112.4.27.9/mall-back/if_user/store_list"; /** * 接口调用 GET */ public static void httpURLConectionGET() { try { URL url = new URL(GET_URL); // 把字符串转换为URL请求地址 HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接 connection.connect();// 连接会话 // 获取输入流 BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) {// 循环读取流 sb.append(line); } br.close();// 关闭流 connection.disconnect();// 断开连接 System.out.println(sb.toString()); } catch (Exception e) { e.printStackTrace(); System.out.println("失败!"); } } /** * 接口调用 POST */ public static void httpURLConnectionPOST () { try { URL url = new URL(POST_URL); // 将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); // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数) // application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行) connection.connect(); // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容) DataOutputStream dataout = new DataOutputStream(connection.getOutputStream()); String parm = "storeId=" + URLEncoder.encode("32", "utf-8"); //URLEncoder.encode()方法 为字符串进行编码 // 将参数输出到连接 dataout.writeBytes(parm); // 输出完成后刷新并关闭流 dataout.flush(); dataout.close(); // 重要且易忽略步骤 (关闭流,切记!) System.out.println(connection.getResponseCode()); // 连接发起请求,处理服务器响应 (从连接获取到输入流并包装为bufferedReader) BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder sb = new StringBuilder(); // 用来存储响应数据 // 循环读取流,若不到结尾处 while ((line = bf.readLine()) != null) { sb.append(bf.readLine()); } bf.close(); // 重要且易忽略步骤 (关闭流,切记!) connection.disconnect(); // 销毁连接 System.out.println(sb.toString()); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { // httpURLConectionGET(); httpURLConnectionPOST(); } }
直接测试,ok 输出的sb值,就是接口返回的Y或者N!
问题补充:
// 解gzip码
public static InputStream unGzip(InputStream in) { try { GZIPInputStream gzip = new GZIPInputStream(in); byte[] buf = new byte[1024]; int len; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((len = gzip.read(buf)) != -1) { baos.write(buf, 0, len); } byte[] b = baos.toByteArray(); ByteArrayInputStream bs = new ByteArrayInputStream(b); baos.flush(); baos.close(); gzip.close(); return new DataInputStream(bs); } catch (Exception e) { e.printStackTrace(); } return null; }
相关推荐
HttpURLConnection调用三方HTTP接口,带有FILE文件参数
HttpUrlConnection对象模拟POST带JSON字符串的AJAX请求失败! 我的目的是抓取响应结果字符串"301",但抓取的结果是一堆HTML代码,哪位大神看看哪有毛病?
HttpURLConnection实现三方接口HTTP调用调用,带有FILE文件参数
调用URL对象的openConnection( )来获取HttpURLConnection对象实例: HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 设置HTTP请求使用的方法:conn.setRequestMethod("GET"); 设置连接超时,...
HttpURLConnection的get,post和图片加载
主要介绍了java后台调用HttpURLConnection类模拟浏览器请求实例,该实例可用于接口调用,具有一定的实用价值,需要的朋友可以参考下
主要介绍了Android中使用HttpURLConnection实现GET POST JSON数据与下载图片,需要的朋友可以参考下
使用HttpURLConnection直接调用.net的WebService
使用HttpURLConnection AsyncTask访问webservice接口(返回json字符串).rar,太多无法一一验证是否可用,程序如果跑不起来需要自调,部分代码功能进行参考学习。
android使用Java原生httpUrlConnection进行get请求
Java原生HttpUrlConnection访问WebService实例,附相关jar包...新手整理不喜勿喷
这是一个关于httpurlconnection 的网络post get 图片下载的Demo
Android HttpUrlConnection使用方法 post and get json.
HttpURLConnectionTest_Get_Post 里面包含HttpURLConnection实现的Get和post方法
android使用HTTPURLconnection/get方法访问HTTP 详细介绍https://mp.csdn.net/postedit/80146506
Java自带的HttpURLConnection访问接口文件上传, 含普通参数值传递和文件传递
httpurlconnection, http post, http get
使用HttpURLConnection或HttpClient方式传json值到spring中
java HttpURLConnection示例 HttpURLConnection工具