详细代码如下

 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. Ceph源码解析:读写流程

    转载注明出处,整理也是需要功夫的,http://www.cnblogs.com/chenxianpao/p/5572859.html 一.OSD模块简介 1.1 消息封装:在OSD上发送和接收信息. ...

  2. ashx 下载文件

    ashx后台 byte[] file =GetFileByte(""); Response.ContentType = "application/octet-stream ...

  3. android sdk下载SDK Platform失败记录

    在使用android sdk manager下载的时候会遇到 下载完毕后,你可能会出现如下图一样的错误,就算重复尝试多次依然无法正常安装 Downloading SDK Platform Androi ...

  4. axios put and patch

    window.axios.patch('https://fir-3-test-2332e.firebaseio.com/notes/' + this.$route.params.key + '.jso ...

  5. Springboot配置文件加载顺序

    使用Springboot开发的时候遇到了配置的问题,外部config里的配置文件本来没有配置https怎么启动还是https呢,原来开发中测试https在classpath路径的配置文件添加https ...

  6. xcode 修改 organization name 和 company identifier

    一:修改 organization name  在终端下 defaults write com.apple.Xcode PBXCustomTemplateMacroDefinitions '{ORGA ...

  7. [读后感]spring Mvc 教程框架实例以及系统演示下载

    [读后感]spring Mvc 教程框架实例以及系统演示下载 太阳火神的漂亮人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致&qu ...

  8. 算法笔记_093:蓝桥杯练习 Problem S4: Interesting Numbers 加强版(Java)

    目录 1 问题描述 2 解决方案   1 问题描述 Problem Description We call a number interesting, if and only if: 1. Its d ...

  9. taro 创建 Tabbar

    1.代码 src/app.js import '@tarojs/async-await' import Taro, { Component } from '@tarojs/taro' import H ...

  10. lodash获取数组或对象的值 at

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