方法
① get(url)
② get(url, bm)
③ post(url, data)
④ post(url, data, bm)
⑤ request(method, url, data, bm)
参数
名称 | 注释 |
---|---|
method | 请求方法GET POST
|
url | 网址 |
bm | 网页编码 |
data | 提交的数据 |
新建http.mjava
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public static String get(String u){
return get(u,"utf-8");
}
public static String get(String u, String bm){
return request("GET",u,null,bm);
}
public static String post(String u, String data){
return post(u,data,"utf-8");
}
public static String post(String u, String data, String bm){
return request("POST",u,data,bm);
}
public static String request(String method, String u, String data, String bm){
String response = null;
try{
URL url = new URL(u);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setConnectTimeout(15000);
conn.setReadTimeout(15000);
if(method.equals("POST")){
OutputStream os = conn.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeBytes(data);
}
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, bm));
StringBuilder sb = new StringBuilder();
String line;
while((line=br.readLine())!=null) sb.append(line+"\n");
response=sb.toString().trim();
br.close();
conn.disconnect();
}
catch(Exception e){}
return response;
}
iyu调用
GET
t()
{
s url=xxx
call(res,"mjava","http.get",url)
syso(res)
}
POST
t()
{
s url=xxx
//data k=v&k1=v1
s data=xxx
call(res,"mjava","http.post",url,data)
syso(res)
}
网友评论