HTTP请求
2021-04-19 16:26
标签:发送请求 methods 信息 测试 parameter lis nts com sys 通过JAVA代码进行HTTP请求的发送 HTTP请求 标签:发送请求 methods 信息 测试 parameter lis nts com sys 原文地址:https://www.cnblogs.com/rzbwyj/p/12267640.html在没有页面的情况下来获取接口返回的数据(一般都是为JSON),我们可以通过一些工具模拟HTTP请求
服务端模拟HTTP请求
1.准备依赖
2.创建post和get方式请求的方法
package com.ty.http;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MyHttpClient {
private static void myPost() throws IOException {
//建立连接请求
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建post请求
HttpPost httpPost = new HttpPost("http://eureka7002.com:6061/myServlet");
//创建参数队列
List
4.get测试百度返回结果
5.post测试本机的另一个服务
5.1给项目准备依赖
5.2创建一个Servlet,接收一个参数,返回json串
package com.ty.servlet;
import com.alibaba.fastjson.JSON;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/myServlet")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String userName = req.getParameter("userName");
resp.setHeader("Content-type", "text/html;charset=UTF-8");
System.out.println("接受到的数据:"+userName);
String json="成功响应";
resp.getWriter().write(JSON.toJSONString(json));
}
}