Java调接口的一些方法

URLEncoder.encode(json, "utf-8");可将中文转码

基础不好只能每次调接口的时候都去网上找方法==!,记录下。

//post传json参数
public static String load(String url,JSONObject query) throws Exception{

System.out.println(url);

URL restURL = new URL(url);

       HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();

       conn.setRequestMethod("POST");
       conn.setRequestProperty("Content-Type","application/json");

       conn.setDoOutput(true);

       conn.setAllowUserInteraction(false);
       
       
       

       PrintStream ps = new PrintStream(conn.getOutputStream());
       ps.print(query);

       ps.close();

       
       BufferedReader bReader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
           
       
       String line,resultStr="";

       while(null != (line=bReader.readLine()))

      {
       
       resultStr +=line;

      }

       bReader.close();

       return resultStr;

  }



//post传json参数返回gzip压缩数据
public static String gzipload(String url,JSONObject query) throws Exception{

URL restURL = new URL(url);

       HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();

       conn.setRequestMethod("POST");
       conn.setRequestProperty("Content-Type","application/json");

       conn.setDoOutput(true);

       conn.setAllowUserInteraction(false);
       
       
       

       PrintStream ps = new PrintStream(conn.getOutputStream());
       ps.print(query);

       ps.close();

       ByteArrayOutputStream out = new ByteArrayOutputStream();
       GZIPInputStream ungzip = new GZIPInputStream(conn.getInputStream());
       byte[] buffer = new byte[256];
       int n;
       while ((n = ungzip.read(buffer)) >= 0) {
      out.write(buffer, 0, n);
      }
       
       return out.toString("utf-8");
       

  }



//post传map参数
public static String httpPost(String urlStr,Map<String,String> params){
        URL connect;
        StringBuffer data = new StringBuffer();  
       try {  
           connect = new URL(urlStr);  
           HttpURLConnection connection = (HttpURLConnection)connect.openConnection();  
           connection.setRequestMethod("POST");  
           connection.setDoOutput(true);
           connection.setDoInput(true);
           connection.setUseCaches(false);//post不能使用缓存
           connection.setInstanceFollowRedirects(true);
           connection.setRequestProperty("accept", "*/*");
           connection.setRequestProperty("connection", "Keep-Alive");
           connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
           OutputStreamWriter paramout = new OutputStreamWriter(  
                   connection.getOutputStream(),"UTF-8");
           String paramsStr = "";   //拼接Post 请求的参数
          if(params!=null&&params.size()>0){
          for(String param : params.keySet()){
          paramsStr += "&" + param + "=" + params.get(param);
          }
          }

          if(!paramsStr.isEmpty()){
              paramsStr = paramsStr.substring(1);
          }
           paramout.write(paramsStr);  
           paramout.flush();  
           BufferedReader reader = new BufferedReader(new InputStreamReader(  
                   connection.getInputStream(), "UTF-8"));  
           String line;              
           while ((line = reader.readLine()) != null) {          
               data.append(line);            
          }  
         
           paramout.close();  
           reader.close();  
      } catch (Exception e) {  
           // TODO Auto-generated catch block  
           e.printStackTrace();  
      }  
      return data.toString();
  }

  

java调接口需传Object方法

//调用方法,此处params可为任何类型
public static Map<String, Object> getStuffInfo(String url, Map<String, Object> params) throws IOException {
   
       RequestConfig requestConfig = RequestConfig.custom()
              .setSocketTimeout(15000)
              .setConnectTimeout(15000)
              .setConnectionRequestTimeout(15000)
              .build();
       Map<String, Object> map = new HashMap<String, Object>();
       HttpPost httpPost = new HttpPost(url);
       httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
   
  //将参数转化为字节流传输
       ByteArrayOutputStream out = new ByteArrayOutputStream();
       ObjectOutputStream os = new ObjectOutputStream(out);
       os.writeObject(params);
       byte[] s = out.toByteArray();
       httpPost.setEntity(new ByteArrayEntity(s,
               ContentType.create("application/x-www-form-urlencoded", "utf-8")));


       CloseableHttpClient httpClient = HttpClients.createDefault();
       CloseableHttpResponse response = null;
       HttpEntity entity = null;
       byte[] responseContent = null;
       try {
           httpPost.setConfig(requestConfig);
           // 执行请求   获取文件内容
           response = httpClient.execute(httpPost);
           entity = response.getEntity();
           responseContent = EntityUtils.toByteArray(entity);
           map.put("fileByte", responseContent);
           // responseContent = EntityUtils.toString(entity, "UTF-8"); //如果需要返回字符串改这里就行了
           //获取文件名
           Header contentHeader = response
                  .getFirstHeader("Content-Disposition");
           if (contentHeader != null) {
               HeaderElement[] values = contentHeader.getElements();
               if (values.length == 1) {
                   NameValuePair param = values[0]
                          .getParameterByName("filename");
                   if (param != null) {
                       String fileName = new String(param.getValue()
                              .toString().getBytes("ISO-8859-1"),
                               "GBK");
                       map.put("fileName", fileName);
                  }
              }
          }
      } catch (Exception e) {
           e.printStackTrace();
      } finally {
           try {
               // 关闭连接,释放资源
               if (response != null) {
                   response.close();
              }
               if (httpClient != null) {
                   httpClient.close();
              }
          } catch (IOException e) {
               e.printStackTrace();
          }
      }
       return map;
  }


//接收方法
@RequestMapping(value = "/construct1", method = RequestMethod.POST)
public void construct1(HttpServletRequest request, HttpServletResponse response) throws Exception {
   //获取传输字节流
   byte[] s = readStream(request.getInputStream());
   ByteInputStream byteInputStream = new ByteInputStream(s,s.length);
   ObjectInputStream objectInputStream = new ObjectInputStream(byteInputStream);
   //强转为既定类
   Map<String,Object> map = (Map<String,Object>) objectInputStream.readObject();
   JSONObject j = (JSONObject) map.get("content");
   JSONObject t = (JSONObject) j.get("F_sqjgmc");
   TextRenderData trd = (TextRenderData) t.get("data");
   return;
}
 
 
posted @   sumling  阅读(217)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示