Java模拟Post和get请求并处理返回字符串

0x01 准备

tomcat(搭建服务器Servlet用于测试返回)

maven(可有可无,有就添加依赖,无则导入相关包(httpclient的相关包))

 

所需包(httpclient和相关依赖,fastjson(处理json数据))

jar包下载

 

无maven

考虑到有人可能就用其中的一些包,就分开给出下载地址

(httpclient+fastjson)

链接: https://pan.baidu.com/s/1xepP_Ys0aMJDxlVJxhUBHQ 提取码: 8djf

(fastjson)

链接: https://pan.baidu.com/s/1ZTkMtpem3HeF8q1KPvRIiA 提取码: rekk

(httpclient)

链接: https://pan.baidu.com/s/16BIQx8inPYc_miKDbZrfyQ 提取码: diw4

 

有maven

添加相关依赖

(httpclient)


    org.apache.httpcomponents
    httpclient
    4.5.3

(fastjson)


    com.alibaba
    fastjson
    1.2.58

0x02

环境准备

编写服务器端(tomcat)

在maven上引入fastjson

Java模拟Post和get请求并处理返回字符串_第1张图片

编写person(Javabean)

package bean;

import java.util.Map;

public class Person {
	private String name;
	private char sex;
	private int age;
	private String mail;
	private String phone;
	private Map data;
	public Map getData() {
		return data;
	}
	public void setData(Map data) {
		this.data = data;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public char getSex() {
		return sex;
	}
	public void setSex(char sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getMail() {
		return mail;
	}
	public void setMail(String mail) {
		this.mail = mail;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getMethod() {
		return method;
	}
	public void setMethod(String method) {
		this.method = method;
	}
	private String method;
	
}

编写PandGs类(servlet返回json文本)

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter out = response.getWriter();
		String pString=request.getParameter("pw");
		if(pString==null){
			Person person=new Person();
			person.setAge(10);
			person.setMail("[email protected]");
			person.setName("Little Ming");
			person.setPhone("88888888");
			person.setSex('M');
			person.setMethod("GET");
			String text=JSON.toJSONString(person);
			out.println(text);
			out.flush();
			out.close();
		}else {
			Person person=new Person();
			person.setAge(10);
			person.setMail("[email protected]");
			person.setName("Little Ming");
			person.setPhone("88888888");
			person.setSex('M');
			person.setMethod("GET");
			person.setData(request.getParameterMap());
			String text=JSON.toJSONString(person);
			out.println(text);
			out.flush();
			out.close();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String pString=request.getParameter("pw");
		if(pString==null){
			Person person=new Person();
			person.setAge(10);
			person.setMail("[email protected]");
			person.setName("Little Fang");
			person.setPhone("77777777");
			person.setSex('F');
			person.setMethod("Post");
			String text=JSON.toJSONString(person);
			out.println(text);
			out.flush();
			out.close();
		}else {
			Person person=new Person();
			person.setAge(10);
			person.setAge(10);
			person.setMail("[email protected]");
			person.setName("Little Fang");
			person.setPhone("77777777");
			person.setSex('F');
			person.setMethod("Post");
			person.setData(request.getParameterMap());
			String text=JSON.toJSONString(person);
			out.println(text);
			out.flush();
			out.close();
		}
	}

0x03编写模拟类

导入包(无maven导入)

Java模拟Post和get请求并处理返回字符串_第2张图片

测试类

Get方法不提交数据

public static void main(String[]args) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			//创建Get链接并且得到返回的字符串
		    HttpGet httpGet = new HttpGet("http://localhost:8080/PandG/PandGs");
		    CloseableHttpResponse response = httpclient.execute(httpGet);
		    HttpEntity entity = response.getEntity();
            String string=EntityUtils.toString(entity);
            System.out.println(string);
            
            //{"age":10,"mail":"[email protected]","method":"GET","name":"Little Ming","phone":"88888888","sex":"M"}
            //fastjson解析string成为object
            JSONObject jObject=JSON.parseObject(string);
            //获取类里面的成员并且输出
            System.out.println("姓名是:"+jObject.getString("name"));
            System.out.println("年龄"+jObject.getString("age"));
            System.out.println("请求方法"+jObject.getString("method"));
            /*
             * 姓名是:Little Ming
             * 年龄10
             * 请求方法GET
             */
	}catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}

Get方法提交数据

方法1(直接在url后加)

public static void main(String[]args) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			//创建Get链接并且得到返回的字符串
		    HttpGet httpGet = new HttpGet("http://localhost:8080/PandG/PandGs?pw=123");
		    CloseableHttpResponse response = httpclient.execute(httpGet);
		    HttpEntity entity = response.getEntity();
            String string=EntityUtils.toString(entity);
            System.out.println(string);
            
            //{"age":10,"data":{"pw":["123"]},"mail":"[email protected]","method":"GET","name":"Little Ming","phone":"88888888","sex":"M"}
            //fastjson解析string成为object
            JSONObject jObject=JSON.parseObject(string);
            //获取类里面的成员并且输出
            System.out.println("姓名是:"+jObject.getString("name"));
            System.out.println("年龄"+jObject.getString("age"));
            System.out.println("请求方法"+jObject.getString("method"));
            System.out.println("提交的数据是"+jObject.getJSONObject("data").getJSONArray("pw").toString());
            /*
             * 姓名是:Little Ming
             *年龄10
             *请求方法GET
             *提交的数据是["123"]
             */
	}catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}

方法2

	public static void main(String[]args) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			//创建Get链接并且得到返回的字符串
			URI uri=new URIBuilder("http://localhost:8080/PandG/PandGs").setParameter("pw", "12345").build();
		    HttpGet httpGet=new HttpGet(uri);
		    CloseableHttpResponse response = httpclient.execute(httpGet);
		    HttpEntity entity = response.getEntity();
            String string=EntityUtils.toString(entity);
            System.out.println(string);
            
            //{"age":10,"data":{"pw":["12345"]},"mail":"[email protected]","method":"GET","name":"Little Ming","phone":"88888888","sex":"M"}
            //fastjson解析string成为object
            JSONObject jObject=JSON.parseObject(string);
            //获取类里面的成员并且输出
            System.out.println("姓名是:"+jObject.getString("name"));
            System.out.println("年龄"+jObject.getString("age"));
            System.out.println("请求方法"+jObject.getString("method"));
            System.out.println("提交的数据是"+jObject.getJSONObject("data").getJSONArray("pw").toString());
            /*
             * 姓名是:Little Ming
             *年龄10
             *请求方法GET
             *提交的数据是["12345"]
             */
	}catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}

Post提交数据(键值对)

方法1

只需把HttpGet改成HttpPost

public static void main(String[]args) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			//创建Get链接并且得到返回的字符串
			URI uri=new URIBuilder("http://localhost:8080/PandG/PandGs").setParameter("pw", "12345").build();
		    HttpPost httpPost=new HttpPost(uri);
		    CloseableHttpResponse response = httpclient.execute(httpPost);
		    HttpEntity entity = response.getEntity();
            String string=EntityUtils.toString(entity);
            System.out.println(string);
            
            //{"age":10,"data":{"pw":["12345"]},"mail":"[email protected]","method":"Post","name":"Little Fang","phone":"77777777","sex":"F"}
            //fastjson解析string成为object
            JSONObject jObject=JSON.parseObject(string);
            //获取类里面的成员并且输出
            System.out.println("姓名是:"+jObject.getString("name"));
            System.out.println("年龄"+jObject.getString("age"));
            System.out.println("请求方法"+jObject.getString("method"));
            System.out.println("提交的数据是"+jObject.getJSONObject("data").getJSONArray("pw").toString());
            /*
             * 姓名是:Little Fang
             *年龄10
             *请求方法Post
             *提交的数据是["12345"]
             */
	}catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}
}

方法2

	public static void main(String[]args) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			//创建Get链接并且得到返回的字符串
			 HttpPost httpPost = new HttpPost("http://localhost:8080/PandG/PandGs");
	            List  nvps = new ArrayList ();
	            nvps.add(new BasicNameValuePair("name", "Little Fang"));
	            nvps.add(new BasicNameValuePair("pw", "123123"));
	            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
	            CloseableHttpResponse response = httpclient.execute(httpPost);
		    HttpEntity entity = response.getEntity();
            String string=EntityUtils.toString(entity);
            System.out.println(string);
            
            //{"age":10,"data":{"name":["Little Fang"],"pw":["123123"]},"mail":"[email protected]","method":"Post","name":"Little Fang","phone":"77777777","sex":"F"}
            //fastjson解析string成为object
            JSONObject jObject=JSON.parseObject(string);
            //获取类里面的成员并且输出
            System.out.println("姓名是:"+jObject.getString("name"));
            System.out.println("年龄"+jObject.getString("age"));
            System.out.println("请求方法"+jObject.getString("method"));
            System.out.println("提交的数据是"+jObject.getJSONObject("data").getJSONArray("pw").toString());
            /*
             * 姓名是:Little Fang
             *年龄10
             *请求方法Post
             *提交的数据是["123123"]
             */
	}catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}
}

Httpclient默认的User-Agent是Apache-HttpClient/4.5.3 (Java/1.8.0_241)

我们是可以修改的

用HttpPost或者HttpGet类里面的setHeader()方法就可以解决

你可能感兴趣的:(技术)