详细代码如下

 package testproject;

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import net.sf.json.JSONObject; /**
* @author mrjade
* @version 创建时间:2017年8月3日
* 类说明:GET,POST请求接口测试
*/
public class HttpInterfaceTest {
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是name1=value1&name2=value2的形式。
* @return URL所代表远程资源的响应
*/ public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlName = url + "?" + param;
System.out.println("Get请求接口:" + urlName);
URL realUrl = new URL(urlName);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 建立实际的连接
conn.connect();
// 获取所有响应头字段
Map<String, List<String>> map = conn.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += "\n" + line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
} /**
* 向指定URL发送POST方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是name1=value1&name2=value2的形式或者是json。
* @return URL所代表远程资源的响应
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += "\n" + line;
}
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
} // 调用天气预报接口请求地址
String getUrl = "http://api.ip138.com/weather";
// 调用天气预报接口请求参数
String getParams = "&code=350229" + "&callback=find" + "&type=1"
+ "&token=cc87f3c77747bccbaaee35006da1ebb65e0bad57"; // 调用天气预报接口请求参数方式一
String postUrl = "http://op.juhe.cn/onebox/weather/query";
String postParamsOne = "&cityname=上海市" + "&key=1234567890";
// 调用天气预报接口请求参数方式二
String postParamsTwo = "{'cityname':'上海市'," + "'key':'1234567890'}";
JSONObject jsonPostParamsTwo = JSONObject.fromObject(postParamsTwo); // 提供主方法,测试发送GET请求和POST请求
@Test
public void test() {
// 发送GET请求
String getResult = HttpInterfaceTest.sendGet(getUrl, getParams);
System.out.println("GET请求参数:" + postParamsOne);
System.out.println("GET请求响应结果:" + getResult);
// 发送POST请求
String postResultOne = HttpInterfaceTest.sendPost(postUrl, postParamsOne);
System.out.println("POST请求参数一:" + postParamsOne);
System.out.println("POST请求响应结果:" + postResultOne);
// 发送POST请求
String postResultTwo = HttpInterfaceTest.sendPost(postUrl, jsonPostParamsTwo.toString());
System.out.println("POST请求参数二:" + jsonPostParamsTwo);
System.out.println("POST请求响应结果:" + postResultTwo);
}
}

测试结果如下

Post+Get方式接口测试代码编写的更多相关文章

  1. 无感知的用同步的代码编写方式达到异步IO的效果和性能,避免了传统异步回调所带来的离散的代码逻辑和陷入多层回调中导致代码无法维护

    golang/goroutine 和 swoole/coroutine 协程性能测试对比 - Go语言中文网 - Golang中文社区 https://studygolang.com/articles ...

  2. 使用Spring注解来简化ssh框架的代码编写

     目的:主要是通过使用Spring注解的方式来简化ssh框架的代码编写. 首先:我们浏览一下原始的applicationContext.xml文件中的部分配置. <bean id="m ...

  3. 如何优雅的代码编写 AutoLayout

    概述 使用 Objective-C 纯代码编写 AutoLayout,看 AutoLayout 的字面理解就是自动布局,听起来好像蛮屌的样子.说白了就是适配:适应.兼容各种不同的情况,包括不同版本的操 ...

  4. 使用python制作ArcGIS插件(2)代码编写

    使用python制作ArcGIS插件(2)代码编写 by 李远祥 上一章节已经介绍了如何去搭建AddIn的界面,接下来要实现具体的功能,则到了具体的编程环节.由于使用的是python语言进行编程,则开 ...

  5. php 代码编写规范

    1 编写目的为了更好的提高技术部的工作效率,保证开发的有效性和合理性,并可最大程度的提高程序代码的可读性和可重复利用性,指定此规范.开发团队根据自己的实际情况,可以对本规范进行补充或裁减. 2 整体要 ...

  6. OC开发_代码片段——代码编写自定义的tableViewCell

    一.介绍 之前已经实现过通过简单的XIB文件来自定义我们的tableViewCell,包括每一步的步骤和代码:http://www.cnblogs.com/daomul/p/4355999.html ...

  7. 这些HTML、CSS知识点,面试和平时开发都需要 No10-No11(知识点:表格操作、代码编写规则)

    系列知识点汇总 1.基础篇 这些HTML.CSS知识点,面试和平时开发都需要 No1-No4(知识点:HTML.CSS.盒子模型.内容布局) 这些HTML.CSS知识点,面试和平时开发都需要 No5- ...

  8. Java学习---Java代码编写规范

    编码规范 1 前言为确保系统源程序可读性,从而增强系统可维护性,java编程人员应具有基本类似的编程风格,兹制定下述Java编程规范,以规范系统Java部分编程.系统继承的其它资源中的源程序也应按此规 ...

  9. 14条最佳JS代码编写技巧

    http://gaohaixian.blog.163.com/blog/static/123260105201142645458315/写任何编程代码,不同的开发者都会有不同的见解.但参考一下总是好的 ...

随机推荐

  1. ubuntu下cmake自动化编译的一个例子

    一个CMakeLists.txt的例子参考:https://www.hahack.com/codes/cmake/https://blog.csdn.net/afei__/article/detail ...

  2. 关于windows下自带的forfile批量删除文件bat命令

    最近在开发的过程中,为了节省资源,需要用到windows下批量删除文件的批处理命令,也就是bat 主要内容: forfiles /p "E:\pictures" /m * /d - ...

  3. [Android Pro] Notification的使用

    Android 4.0以前: 1: 普通的notification private static final int NOTIFY_ID = 0; notificationManager = (Not ...

  4. 前端性能优化:使用Array.prototype.join代替字符串连接

    来源:GBin1.com 有一种非常简单的客户端优化方式,就是用Array.prototype.join代替原有的基本的字符连接的写法.在这个系列的第一篇中,我在代码中使用了基本字符连接: htmlS ...

  5. 使用iOS-QR-Code-Encoder 生成二维码

    一:所需类库 iOS-QR-Code-Encoder 官网主页:https://github.com/moqod/iOS-QR-Code-Encoder 导入:QuartzCore.framework ...

  6. css网页单位

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  7. 从零開始开发Android版2048 (三)逻辑推断

    近期工作比較忙,所以更新的慢了一点,今天的主要内容是关于Android版2048的逻辑推断,经过本篇的解说,基本上完毕了这个游戏的主体部分. 首先还是看一下,我在实现2048时用到的一些存储的数据结构 ...

  8. 用Markdown写博客快速入门

    Markdown,简单来说,就是一种可以方便转换为HTML的带标记符号纯文本. 它是对我等键盘党的福音:我不用再费劲挪动鼠标去按加粗.设置段落了,用键盘输入所有文本,一气呵成. 最重要的是,cnblo ...

  9. 理解和使用 Promise.all 和 Promise.race

    一.Pomise.all的使用 Promise.all可以将多个Promise实例包装成一个新的Promise实例.同时,成功和失败的返回值是不同的,成功的时候返回的是一个结果数组,而失败的时候则返回 ...

  10. vue vuex 大型项目demo示例

    1.vuex 动态模块配置 import Vue from 'vue' import Vuex from 'vuex' import store from '@/store'; // 使用Vuex插件 ...