从一个action地址获取信息

时间:2023-03-09 19:27:20
从一个action地址获取信息

get方法

String url_str ="http://127.0.0.1:8400/lxyyProduct/getProductUserNeedUpdate.action?ts="+maxTs;
URL url = new URL(url_str);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
int result = connection.getResponseCode(); if (result == )//如果等于200算连接成功
{
InputStream in;
in = connection.getInputStream();
BufferedReader breader = new BufferedReader(new InputStreamReader(in , "UTF-8"));
String str=breader.readLine();
}

post方法

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL; public class HttpUrlUtil { /**
* 通过HttpURLConnection模拟post表单提交
*
* @param path
* @param params 例如"name=zhangsan&age=21"
* @return
* @throws Exception
*/
public static String sendPostRequestByForm(String path, String params) throws Exception{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");// 提交模式
// conn.setConnectTimeout(10000);//连接超时 单位毫秒
// conn.setReadTimeout(2000);//读取超时 单位毫秒
conn.setDoOutput(true);// 是否输入参数
byte[] bypes = params.toString().getBytes();
conn.getOutputStream().write(bypes);// 输入参数
InputStream inStream=conn.getInputStream();
return readInputStream(inStream);
} /**
* 从输入流中读取数据
* @param inStream
* @return
* @throws Exception
*/
public static String readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[];
int len = ;
while( (len = inStream.read(buffer)) !=- ){
outStream.write(buffer, , len);
}
byte[] data = outStream.toByteArray();//网页的二进制数据
outStream.close();
inStream.close(); String res = new String(data,"UTF-8"); return res;
} public static void main(String[] args) throws UnsupportedEncodingException, Exception
{
String path="http://www.kd185.com/ems.php";
String params="id=1&df=323"; System.out.println(sendPostRequestByForm(path,params));
}
}