Java 实现 客户端 HttpURLConnection
前段时间一直忙着实现web服务器,但是苦于没有好的办法测试服务器的接口,所以通过到处的资料收集,我终于找到了再Java端实现HttpURLConnection创建的方法。
首先新建Java类,再该类中编写main方法,通过编写Thread线程完成客户端的启动。
在线程的run方法中,声明HttpURLConnection和BufferedReader的对象,并使用URL的对象存放访问服务器资源的路径。通过HttpURLConnection的对象设置访问服务器的方式为"POST",设置相关连接参数后使用httpURLConnection.connect()建立连接或者调用httpURLConnection.getOutputStream()隐含连接,如下图所示。
使用DataOutputStream对象调用writeBytes方法给服务器发送请求数据,使用StringBuilder对象接收服务器的回复数据,并进行相应逻辑判断,如图所示。
相关代码如下
public class HttpClientText
{
static public void main(String[] agrs)
{
new Thread(new Runnable()
{
@Override
public void run()
{
HttpURLConnection httpURLConnection = null;
BufferedReader reader = null;
try
{
URL url = new URL("http://192.168.3.7:80/AndroidService/Login");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在
// http正文内,因此需要设为true, 默认情况下是false;
httpURLConnection.setDoOutput(true);
// 设置是否从httpUrlConnection读入,默认情况下是true;
httpURLConnection.setDoInput(true);
// Post 请求不能使用缓存
httpURLConnection.setUseCaches(false);
ttpURLConnection.setConnectTimeout(8000);
httpURLConnection.setReadTimeout(8000);
// // 建立连接
// httpURLConnection.connect();
// 此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,
// 所以在开发中不调用上述的connect()也可以)。
DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
// 消息包中 发送数据
out.writeBytes("userName=root&passWord=password");
// 接收数据,读取数据
InputStream in = httpURLConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder read = new StringBuilder();
String line;
while((line = reader.readLine()) != null)
{
read.append(line);
}
ine = read.toString();
}catch (Exception e)
{ }
}
}).start();
}
}