此两段代码示例只针对发送参数是json格式有用,类似{"param1":"xxxx","param2":"xxxx"}
java:
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpRequest {
public static String sendPost(String url,String param){
OutputStreamWriter out =null;
BufferedReader reader = null;
StringBuilder response = new StringBuilder();
//创建连接
try {
URL httpUrl = null; //HTTP URL类 用这个类来创建连接
//创建URL
httpUrl = new URL(url);
//建立连接
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("connection", "keep-alive");
conn.setUseCaches(false);//设置不要缓存
conn.setInstanceFollowRedirects(true);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
//POST请求
out = new OutputStreamWriter(
conn.getOutputStream());
out.write(param);
out.flush();
//读取响应
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String lines;
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), StandardCharsets.UTF_8);
response.append(lines);
}
reader.close();
// 断开连接
conn.disconnect();
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(reader!=null){
reader.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return response.toString();
}
public static void main(String[] args) {
JSONObject jsonParam = new JSONObject();
jsonParam.put("phoneNo", "18851024375");
//jsonParam.put("name", "zhangsan");
String param = jsonParam.toJSONString();
String url="http://xxxxx/xxxxx/login/code";
String sendPost = sendPost(url, param);
System.out.println(sendPost);
}
}
注:用到的maven配置
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
python:
class Login(object):
# 发送短信验证码
def sendSmsCode(self, phone):
url_sendSmsCode = 'http://xxxxx/xxxxx/login/code'
headers_sendSmsCode = {"token": "",
"deviceType": "2",
"deviceID": "00000000-100e-9f06-100e-9f0600000000",
"version": "1.0.1",
"skipVersion": "0",
"Content-Type": "application/json;charset=utf-8",
"Content-Length": "25",
"Connection": "Keep-Alive",
"Accept-Encoding": "gzip",
"User-Agent": "okhttp/3.10.0"}
data_sendSmsCode = {"phoneNo": "{}".format(phone)}
try:
r = requests.post(url=url_sendSmsCode, headers=headers_sendSmsCode, json=data_sendSmsCode, verify=False)
# logging.debug(r.json())
if r.json()['code'] == 0 and r.json()['msg'] == "执行成功":
logging.debug("发送短信验证码成功,后续执行截取短信验证码操作")
return "success"
elif r.json()['code'] == 400:
logging.debug("code返回400,检查服务器...")
elif r.json()['code'] == 10003:
logging.debug("请求失败,请60秒后重试")
else:
raise ValueError("超出预期异常,直接退出")
except Exception as e:
pass
网友评论