URL url = new URL("提交的URL");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try
{
connection.setDoInput(true);
connection.setDoOutput(true);
{
// 提交的内容
byte[] requsetContent = new byte[1024];
connection.setRequestProperty("Content-Length", Integer.toString(requsetContent.length));
OutputStream outputStream = connection.getOutputStream();
try
{
// 向外输入流
outputStream.write(requsetContent);
outputStream.flush();
}
catch (Exception ex)
{
throw ex;
}
finally
{
outputStream.close();
}
}
// 获取HTTP相应请求
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
{
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 64);
// 得到返回流
InputStream inputStream = connection.getInputStream();
try
{
byte[] buf = new byte[1024 * 64];
int n;
while ((n = inputStream.read(buf)) >= 0)
{
baos.write(buf, 0, n);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
inputStream.close();
}
// 获取包的内容
byte[] responseContent = baos.toByteArray();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
connection.disconnect();
}
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try
{
connection.setDoInput(true);
connection.setDoOutput(true);
{
// 提交的内容
byte[] requsetContent = new byte[1024];
connection.setRequestProperty("Content-Length", Integer.toString(requsetContent.length));
OutputStream outputStream = connection.getOutputStream();
try
{
// 向外输入流
outputStream.write(requsetContent);
outputStream.flush();
}
catch (Exception ex)
{
throw ex;
}
finally
{
outputStream.close();
}
}
// 获取HTTP相应请求
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
{
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 64);
// 得到返回流
InputStream inputStream = connection.getInputStream();
try
{
byte[] buf = new byte[1024 * 64];
int n;
while ((n = inputStream.read(buf)) >= 0)
{
baos.write(buf, 0, n);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
inputStream.close();
}
// 获取包的内容
byte[] responseContent = baos.toByteArray();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
connection.disconnect();
}
本文介绍了一个使用Java进行网络编程的具体示例,通过HttpURLConnection实现HTTP POST请求并接收响应。示例详细展示了如何设置连接属性、发送请求数据以及读取服务器响应。
337

被折叠的 条评论
为什么被折叠?



