httpclient网络请求常见问题

  • httpclient网络请求常见问题已关闭评论
  • 115,023 views
  • A+
所属分类:编程开发

java网络请经常出现的一段代码,如下:

byte[] buffer = null;

HttpURLConnection conn = null;

try {

conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("POST");

OutputStream os = conn.getOutputStream();

DataOutputStream dos = new DataOutputStream(os);

dos.write(input.getBytes());

dos.flush();

dos.close();

InputStream is = conn.getInputStream();

DataInputStream dis = new DataInputStream(is);

buffer = new byte[dis.available()];

dis.read(buffer);

conn.disconnect();

} catch (IOException e) {

e.printStackTrace();

}

问题1:input.getBytes()没有指定字符集

问题2:dos.close(); stream不能保证释放

问题3:available()只显示当前可读数据大小,返回数据包过大时,数据读不完

问题4:conn.disconnect();连接不能保证释放

问题5:e.printStackTrace(); 日志没有上下文,出现异常不便于分析原因

 

合理安全的代码应该为:

String logCtx = “[url:” + url + “][input:” + input + “]”;

int read = 0;

byte[] buffer = new byte[1024];

HttpURLConnection conn = null;

DataOutputStream dos = null;

DataInputStream dis = null;

ByteArrayOutputStream result = new ByteArrayOutputStream();

try {

long start = System.currentTimeMillis();

conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("POST");

OutputStream os = conn.getOutputStream();

DataOutputStream dos = new DataOutputStream(os);

    dos.write(input.getBytes(“UTF-8”));

InputStream is = conn.getInputStream();

DataInputStream dis = new DataInputStream(is);

  while (-1 != (read = dis.read(buffer))) {

        result.write(buffer, 0, read);

    }

long millis = System.currentTimeMillis() - start;

LOG.i(TAG, logCtx + “[millis:” + millis + “] post done …”);

} catch (IOException e) {

    LOG.e(TAG, logCtx + “ post failed(IOException)”, e);

} finally {

close(dos, dis, conn);

}

  • 安卓客户端下载
  • 微信扫一扫
  • weinxin
  • 微信公众号
  • 微信公众号扫一扫
  • weinxin
avatar