java 模拟get post请求_Java后台模拟发送http的get和post请求,并测试

本文档展示了如何使用Java代码模拟HTTP GET和POST请求。提供了详细的步骤,包括设置请求参数、编码URL、连接到URL并获取响应。还包含一个测试类的概述,用于使用自动化测试工具Gauge进行测试。
摘要由CSDN通过智能技术生成

个人学习使用:谨慎参考

1 Client类

import com.thoughtworks.gauge.Step;

import com.thoughtworks.gauge.Table;

import com.thoughtworks.gauge.TableRow;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLEncoder;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

/**

* Created by KSC on 2/7/2017.

*/

public class testClient {

//send get request

/**

*

* @param url destination address

* @param parametersTable request parameters

* @return remote response result

*/

@Step("the get method url is and parameters are ")

public static String sendGet(String url,Table parametersTable){

Map parameters = new HashMap<>();

for(TableRow row : parametersTable.getTableRows()){

String key = row.getCell("name");

String value = row.getCell("age");

parameters.put(key,value);

}

for (String s: parameters.keySet()){

System.out.println(s+"\t"+parameters.get(s));

}

String result = "";//返回的结果

BufferedReader in = null;//读取响应的输入流

StringBuffer sf = new StringBuffer();//存储参数

String params = "";//编码后的参数

try{

if (parameters.size() == 1){

for(String name : parameters.keySet()){

sf.append(name).append("=").append(

java.net.URLEncoder.encode(parameters.get(name),"UTF-8")

);

}

params = sf.toString();

}else{

for(String name : parameters.keySet()){

sf.append(name).append("=").append(

java.net.URLEncoder.encode(parameters.get(name),"UTF-8")

).append("&");

}

String tempParams = sf.toString();

params = tempParams.substring(0,tempParams.length()-1);

System.out.println(params);

}

String fullUrl = url + "?" + params;

System.out.println(fullUrl);

//创建URL对象

URL connUrl = new URL(fullUrl);

//打开URL链接

HttpURLConnection httpConn = (HttpURLConnection)connUrl.openConnection();

// 设置通用属性

httpConn.setRequestProperty("Accept","*/*");

httpConn.setRequestProperty("Connection","Keep-Alive");

httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");

//建立实际链接

httpConn.connect();

//响应头部的获取

Map> headers = httpConn.getHeaderFields();

System.out.println("==============================");

//遍历头部所有字段

for(String key : headers.keySet()){

System.out.println(key+"\t: \t"+headers.get(key));

}

//定义bufferedReader输入流来读取URL的响应,并设置编码方式

in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));

String line = "";//读取返回的内容

while((line = in.readLine()) != null){

result = result+line;

}

}catch(Exception e){

e.printStackTrace();

}finally{

try{

if(in != null){

in.close();

}

}catch(IOException ex){

ex.printStackTrace();

}

}

System.out.println("*****************************");

System.out.println(result);

System.out.println("==============================");

return result;

}

//send post request

@Step("the post method url is and parameters are ")

public static String sendPost(String url,Table parametersTable){

Map parameters = new HashMap<>();

for(TableRow row : parametersTable.getTableRows()){

String key = row.getCell("name");

String value = row.getCell("age");

parameters.put(key,value);

}

for (String s: parameters.keySet()){

System.out.println(s+"\t\t"+parameters.get(s));

}

System.out.println("---------------------");

String result = "";

BufferedReader in = null;

PrintWriter out = null;//

StringBuffer sf = new StringBuffer();

String params = "";

try{

if (parameters.size() == 1){

for(String name : parameters.keySet()){

sf.append(name).append("=").append(

java.net.URLEncoder.encode(parameters.get(name),"UTF-8")

);

}

params = sf.toString();

}else{

for(String name : parameters.keySet()){

sf.append(name).append("=").append(

java.net.URLEncoder.encode(parameters.get(name),"UTF-8")

).append("&");

}

String tempParams = sf.toString();

params = tempParams.substring(0,tempParams.length()-1);

}

URL connUrl = new URL(url);

HttpURLConnection httpConn = (HttpURLConnection)connUrl.openConnection();

httpConn.setRequestProperty("Accept","*/*");

httpConn.setRequestProperty("Connection","Keep-Alive");

httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");

//设置post方式

httpConn.setDoInput(true);

httpConn.setDoOutput(true);

//获取HttpUrlConnection对象对应的输出流

out = new PrintWriter(httpConn.getOutputStream());

//发送请求参数

out.write(params);

//flush(冲洗)输出流中的缓冲

out.flush();

in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));

String line = "";

while((line = in.readLine()) != null){

result = result+line;

}

}catch(Exception e){

e.printStackTrace();

}finally{

try{

if(out != null){

out.close();

}

if(in != null){

in.close();

}

}catch(IOException e){

e.printStackTrace();

}

}

System.out.println("*****************************");

System.out.println(result);

System.out.println("============================");

return result;

}

}

2.测试类

用自动化测试工具gauge进行测试

Use http request for creating user

=====================

Created by KSC on 2/7/2017

This is an executable specification file which follows markdown syntax.

Every heading in this file denotes a scenario. Every bulleted point denotes a step.

call on url with method get

----------------

tags: get

*the get method url is "http://localhost:8080" and parameters are

|name|age|

|----|---|

|tom|20|

|maike|22|

call on url with method post

---------------------------

tags: post

*the post method url is "https://www.baidu.com/" and parameters are

|name|age|

|----|---|

|marry|20|

|rose|22|

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用HttpURLConnection或者HttpClient来发送get和post请求到微信接口。以下是示例代码: 使用HttpURLConnection发送get请求: ```java URL url = new URL("https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString()); } else { System.out.println("GET request failed, response code: " + responseCode); } ``` 使用HttpURLConnection发送post请求: ```java String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); // 设置post请求参数 String urlParameters = "json data..."; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString()); } else { System.out.println("POST request failed, response code: " + responseCode); } ``` 使用HttpClient发送get请求: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID"); CloseableHttpResponse response = httpClient.execute(httpGet); try { HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); System.out.println(responseBody); } finally { response.close(); } ``` 使用HttpClient发送post请求: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN"); // 设置post请求参数 StringEntity entity = new StringEntity("json data...", ContentType.APPLICATION_JSON); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity responseEntity = response.getEntity(); String responseBody = EntityUtils.toString(responseEntity, "UTF-8"); EntityUtils.consume(responseEntity); System.out.println(responseBody); } finally { response.close(); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值