Android 发送http请求实例

来源:互联网 发布:黑客帝国台词 知乎 编辑:程序博客网 时间:2024/06/08 18:08
           URL url;try {OutputStream os = null;url = new URL(uri);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setDoOutput(true);conn.setDoInput(true);conn.setRequestMethod("POST");conn.setFixedLengthStreamingMode(packetData.length);conn.setUseCaches(false);os = conn.getOutputStream();int offset = 0;int len = READ_WRITE_SIZE;while (offset < packetData.length){if (offset + len > packetData.length){len = packetData.length - offset;}os.write(packetData, offset, len);os.flush();offset += len;}InputStream fin = null;fin = conn.getInputStream();BufferedReader r = new BufferedReader(new InputStreamReader(fin)); StringBuilder total = new StringBuilder(); String line; while ((line = r.readLine()) != null) {     total.append(line); }tv.setText("---> "+total);} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}

需要注意的是不能在主线中进行http请求,需要

new Thread(mRun).start();  Runnable mRun = new Runnable(){}


0 0
原创粉丝点击