今天讲了网络相关的知识,将自己的投票系统部署在服务器上,告诉大家如果使用java代码模拟登陆,并能返回对应的数据活来。
以下是代码:
package com.yc.case1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
*
* @author Lydia
*
*/
public class PostDemo {
public static void main(String[] args) throws IOException {
URL url =new URL("http://192.168.1.176:8080/vote/user.action");
//获取httpUrlConnection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置post请求
connection.setRequestMethod("POST");
//设置超时时间
connection.setConnectTimeout(3000);
connection.setDoInput(true);
connection.setDoOutput(true);
//设置是否使用缓存
connection.setUseCaches(false);
//设置是否自动重定向
connection.setInstanceFollowRedirects(true);
//模拟表单,。post
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//连接
connection.connect();
//写入参数到请求中
String params ="userName=a3242435435&password=a&op=login";
OutputStream out =connection.getOutputStream() ;
out.write(params.getBytes()); //以字节数组
out.flush();
out.close();
//从连接中读取响应的信息
String msg="";
//获取状态吗
int code = connection.getResponseCode();
if(code==200){
InputStream in =connection.getInputStream();
byte []bt =new byte[1024];
int len =0;
while( (len = in.read(bt))!=-1){
msg +=new String(bt,0,len);
}
in.close();
}
System.out.println(msg);
//断开连接
connection.disconnect();
}
}