生产中遇到过这种问题,记录下java的接口调用问题。

一种是json方式;

 public static String sendPost(String url, JSONObject obj)throws IOException{
OutputStreamWriter out = null;
BufferedReader reader = null;
String response=""; /* String paramStr = "";
if (null != param) { //遍历参数Map添加到集合中
Set<String> keySet = param.keySet();
for (String key : keySet) {
paramStr = paramStr + key + ":" + param.get(key) + "&";
}
}
int lastAndIndex = paramStr.lastIndexOf("&");
if (lastAndIndex != -1) {
paramStr = paramStr.substring(0, lastAndIndex);
} System.out.println("地址===" + url);
System.out.println("入参===" + paramStr);*/ try {
URL httpUrl = null; //HTTP URL类 用这个类来创建连接
//创建URL
httpUrl = new URL(url);
//建立连接
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setRequestProperty("accept", "*/*");// 设置通用的请求属性
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("connection", "keep-alive");
conn.setUseCaches(false);//设置不要缓存
conn.setInstanceFollowRedirects(true);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
//POST请求
out = new OutputStreamWriter(
conn.getOutputStream());
out.write(obj.toJSONString());
out.flush();
//读取响应
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String lines;
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
response+=lines;
}
reader.close();
// 断开连接
conn.disconnect();
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(reader!=null){
reader.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
} return response;
}

再来一个普通的str 调用接口;

    /**
* 向指定 URL 发送POST方法的请求
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPostWebReq(String url, Map<String, Object> param,int i) throws Exception {
String paramStr = "";
if (null != param) { //遍历参数Map添加到集合中
Set<String> keySet = param.keySet();
for (String key : keySet) {
paramStr = paramStr + key + "=" + param.get(key) + "&";
}
}
int lastAndIndex = paramStr.lastIndexOf("&");
if (lastAndIndex != -1) {
paramStr = paramStr.substring(0, lastAndIndex);
} System.out.println("地址===" + url);
System.out.println("入参===" + paramStr); PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();// 打开和URL之间的连接
conn.setRequestProperty("accept", "*/*");// 设置通用的请求属性
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setDoOutput(true);// 发送POST请求必须设置如下两行
conn.setDoInput(true);// 获取URLConnection对象对应的输出流
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));// 发送请求参数
out.print(paramStr);// flush输出流的缓冲
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));// 定义BufferedReader输入流来读取URL的响应
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
throw e;
} finally { // 使用finally块来关闭输出流、输入流
try {
if (in != null) in.close();
} catch (IOException ex) { }
if (out != null) out.close();
}
return result;
}

java 接口调用的更多相关文章

  1. OpenCV4Android开发之旅(一)----OpenCV2.4简介及 app通过Java接口调用OpenCV的示例

    转自:  http://blog.csdn.net/yanzi1225627/article/details/16917961 开发环境:windows+ADT Bundle+CDT+OpenCV-2 ...

  2. 十分钟搭建redis单机版 & java接口调用

    本次单机版redis服务器搭建采用的包为redis-3.0.0.tar.gz,主要是记录下安装的心得,不喜勿喷! 一.搭建redis服务器单机版 1.上传redis-3.0.0.tar.gz到服务器上 ...

  3. java接口调用——webservice就是一个RPC而已

    很多新手一听到接口就蒙逼,不知道接口是什么!其实接口就是RPC,通过远程访问别的程序提供的方法,然后获得该方法执行的接口,而不需要在本地执行该方法.就是本地方法调用的升级版而已,我明天会上一篇如何通过 ...

  4. 百度鹰眼Java接口调用增删改查实例

    因感觉百度鹰眼的使用场景比较符合实际业务,于是对百度鹰眼做了简单功能调试.刚开始使用springframework封装的RestTemplate,但是测试提示ak参数不存在.后又试了几种方法,均提示a ...

  5. Java接口调用工具类

    package com.qiyuan.util; import java.io.BufferedReader; import java.io.IOException; import java.io.I ...

  6. 基于JAVA的全国天气预报接口调用示例

    step1:选择本文所示例的接口"全国天气预报接口" url:https://www.juhe.cn/docs/api/id/39/aid/87step2:每个接口都需要传入一个参 ...

  7. bugzilla4的xmlrpc接口api调用实现分享: xmlrpc + https + cookies + httpclient +bugzilla + java实现加密通信下的xmlrpc接口调用并解决登陆保持会话功能

    xmlrpc .  https . cookies . httpclient.bugzilla . java实现加密通信下的xmlrpc接口调用并解决登陆保持会话功能,网上针对bugzilla的实现很 ...

  8. java后台调用HttpURLConnection类模拟浏览器请求(一般用于接口调用)

    项目开发中难免遇到外部接口的调用,小生今天初次接触该类,跟着API方法走了一遍,如有不对的地方,还请哆哆指正,拜谢! 1 package com.cplatform.movie.back.test; ...

  9. C#调用java接口报“Fault occurred while processing”异常问题

    服务在通常项目中总是要用到的C#的webservice.wcf,还有第三方的,比如java服务.一般来说调用都不会有什么问题,因为服务的标准都是一样的.要注意的就是:1.参数个数匹配:2.参数类型和返 ...

随机推荐

  1. 用sed替换文件中的空格

    请教sed 替换问题 请教各位如何替换多个空格为一个字符,如一个文件中间隔符有是一个空格,有的地方是多个空格,想全部用“|”替换,如何处理,请指教 请教sed 替换问题 [code]sed '/ \+ ...

  2. PHP中一些有用的函数

    <?php /** * 加密解密 * * @param string $key * @param string $string * @param string $decrypt * @retur ...

  3. 【LeetCode】104. Maximum Depth of Binary Tree (2 solutions)

    Maximum Depth of Binary Tree  Given a binary tree, find its maximum depth. The maximum depth is the ...

  4. access database in a helper function ?

    <?php if(! function_exists('get_user_info')){ function get_user_info($field) { $ci = & get_in ...

  5. POJ 3006 Dirichlet's Theorem on Arithmetic Progressions (素数)

    Dirichlet's Theorem on Arithmetic Progressions Time Limit: 1000MS   Memory Limit: 65536K Total Submi ...

  6. 使用Android Ant在编译时混淆

    关于ANT 编译和脚本请查看 : http://sinfrancis.javaeye.com/blog/721582 这里使用的是proguard4.4 ,在原有的ANT脚本上加入以下代码: 定义pr ...

  7. 【Linux】X window与文本模式的切换

    Linux默认的情况下会提供六个Terminal来让使用者登陆,切换的方式为:[Ctrl] + [Alt] + [F1]~[F6]的组合按钮.那这六个终端接口如何命名呢,系统会将[F1] ~ [F6] ...

  8. 通俗易懂,C#如何安全、高效地玩转任何种类的内存之Span的脾气秉性(二)。 异步委托 微信小程序支付证书及SSL证书使用 SqlServer无备份下误删数据恢复 把list集合的内容写入到Xml中,通过XmlDocument方式写入Xml文件中 通过XDocument方式把List写入Xml文件

    通俗易懂,C#如何安全.高效地玩转任何种类的内存之Span的脾气秉性(二).   前言 读完上篇<通俗易懂,C#如何安全.高效地玩转任何种类的内存之Span的本质(一).>,相信大家对sp ...

  9. OGG_GoldenGate数据库配置DDL同步(案例)

    2014-03-08 Created By BaoXinjian

  10. Java 异常模型综述

    一. 异常的引入及基础 发现错误的理想时机是在编译阶段.也就是在你试图运行程序之前. 然而,编译期间编译器并不能找出全部的错误,余下的错误仅仅有在运行期才干发现和解决,这类错误就是 Throwable ...