怎么用java模拟http请求

333445... 333445 展开
 我来答
爱吃的肸子
2017-05-18 · TA获得超过2649个赞
知道大有可为答主
回答量:1786
采纳率:54%
帮助的人:293万
展开全部
/*
* 得到返回的内容
*/
public static String getResult(String urlStr, String content) {
URL url = null;
HttpURLConnection connection = null;

try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.connect();

DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(content);
out.flush();
out.close();

BufferedReader reader = new BufferedReader(new InputStreamReader(connection
.getInputStream(), "utf-8"));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
追问:
没注释吗?
追答:
/*
* 得到返回的内容
*/
public static String getResult(String urlStr, String content) {
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();//新建连接实例
connection.setDoOutput(true);//是否打开输出流 true|false
connection.setDoInput(true);//是否打开输入流true|false
connection.setRequestMethod("POST");//提交方法POST|GET
connection.setUseCaches(false);//是否缓存true|false
connection.connect();//打开连接端口
DataOutputStream out = new DataOutputStream(connection.getOutputStream());//打开输出流往对端服务器写数据
out.writeBytes(content);//写数据,也就是提交你的表单 name=xxx&pwd=xxx
out.flush();//刷新
out.close();//关闭输出流
BufferedReader reader = new BufferedReader(new InputStreamReader(connection
.getInputStream(), "utf-8"));//往对端写完数据 对端服务器返回数据 ,以BufferedReader流来读取
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();//关闭连接
}
}
return null;
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式