此兩段代碼示例只針對發(fā)送參數(shù)是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();
//創(chuàng)建連接
try {
URL httpUrl = null; //HTTP URL類 用這個類來創(chuàng)建連接
//創(chuàng)建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("發(fā)送 POST 請求出現(xiàn)異常!"+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):
# 發(fā)送短信驗證碼
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'] == "執(zhí)行成功":
logging.debug("發(fā)送短信驗證碼成功,后續(xù)執(zhí)行截取短信驗證碼操作")
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