最近在用python做接口测试,刚好最近也在学习Java,就尝试用Java发送一下http请求~~~~~~
感觉大多数第一次尝试的时候都是用百度做测试:
向https://www.baidu.com/网址发送get请求
看代码:
get请求
public class HttpURLConnectionDemo {
//get请求
public static void main(String[] args) {
try {
URL url = new URL("https://www.baidu.com/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int reponse = connection.getResponseCode();
String text = connection.getResponseMessage();
System.out.println("响应状态码为:"+reponse+"\tmessage为:"+text);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
post请求:(无参数),访问url为本地服务
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
public class HttpURLConnectionDemo {
public Map<String, List> post(){
Map map = new HashMap();
try{
URL url = new URL("http://192.168.30.35:8080/api/v1/product/manager/page");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
int reponse = connection.getResponseCode();
String text = connection.getResponseMessage();
map.put("code",reponse);
map.put("message",text);
// System.out.println("响应状态码为:"+reponse+"\tmessage为:"+text);
// System.out.println("结果为"+map);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(map);
return map;
}
总结:
当get
和post
请求都无参数时,区别就在于请求方法上:connection.setRequestMethod("POST");
。
给post请求做了一点小优化:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
public class HttpURLConnectionDemo {
//post请求
public Map<String, List> post(){
Map map = null;
try{
URL url = new URL("http://192.168.30.35:8080/api/v1/product/manager/page");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
int reponse = connection.getResponseCode();
String text = connection.getResponseMessage();
map = new HashMap();
map.put("code",reponse);
map.put("message",text);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(map);
return map;
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。