1.发送get请求:
connect可以不写,url.openconnection已经包含了connect功能
public void doGet() { try { URL url = new URL("http://www.baidu.com"); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.connect(); InputStream inputStream = httpURLConnection.getInputStream();//字节输入流 InputStreamReader reader = new InputStreamReader(inputStream);//字符输入流 BufferedReader bufferedReader = new BufferedReader(reader);//带缓冲区的字符输入流 String strLine = null; String strResult = ""; int iCode = httpURLConnection.getResponseCode();//得到状态码,200表示成功 while ((strLine = bufferedReader.readLine()) != null) { strResult += strLine + "\n"; } Log.d("qf", strResult); bufferedReader.close();//关闭流 httpURLConnection.disconnect();//关闭socket连接,如果还要使用这个连接,可以不关闭 } catch (Exception e) { e.printStackTrace(); } }
2.发送post请求:
public void doPost() { try { URL url = new URL("http://zhushou.72g.com/app/game/game_list/"); try { HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.connect(); OutputStream os = httpURLConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); String content = "platform=2"; writer.write(content); writer.flush(); writer.close(); BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8")); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } br.close(); String result = sb.toString(); Log.d("qf", result); } catch (IOException e) { e.printStackTrace(); } } catch (MalformedURLException e) { e.printStackTrace(); } }
3.下载
// 用于异步的显示图片 private Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { //下载成功 case LOAD_SUCCESS: // 获取图片的文件对象 File file = new File(Environment.getExternalStorageDirectory(), "pic.jpg"); FileInputStream fis = null; try { fis = new FileInputStream(file); Bitmap bitmap = BitmapFactory.decodeStream(fis); image.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } break; //下载失败 case LOAD_ERROR: Toast.makeText(MainActivity.this, "加载失败", Toast.LENGTH_SHORT).show(); break; } } ; }; //下载图片的主方法 private void getPicture() { URL url = null; InputStream is = null; FileOutputStream fos = null; try { //构建图片的url地址 url = new URL("http://avatar.csdn.net/C/6/8/1_bz419927089.jpg"); //开启连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置超时的时间,5000毫秒即5秒 conn.setConnectTimeout(5000); //设置获取图片的方式为GET //conn.setRequestMethod("GET"); //响应码为200,则访问成功 if (conn.getResponseCode() == 200) { //获取连接的输入流,这个输入流就是图片的输入流 is = conn.getInputStream(); //构建一个file对象用于存储图片 File file = new File("/sdcard/pic.jpg"); fos = new FileOutputStream(file); int len = 0; byte[] buffer = new byte[1024]; //将输入流写入到我们定义好的文件中 while ((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len); } //将缓冲刷入文件 fos.flush(); //告诉handler,图片已经下载成功 handler.sendEmptyMessage(LOAD_SUCCESS); } } catch (Exception e) { //告诉handler,图片已经下载失败 handler.sendEmptyMessage(LOAD_ERROR); e.printStackTrace(); } finally { //在最后,将各种流关闭 try { if (is != null) { is.close(); } if (fos != null) { fos.close(); } } catch (Exception e) { handler.sendEmptyMessage(LOAD_ERROR); e.printStackTrace(); } } }
4.上传:
public void upload(){ List<String> list = new ArrayList<String>(); list.add("/sdcard/Download/aaa.jpg"); try { String BOUNDARY = "---------7d4a6d158c9"; // 定义数据分隔线 URL url = new URL("http://10.2.152.133/upload.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "Keep-Alive"); //conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); //conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(conn.getOutputStream()); byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线 int leng = list.size(); for(int i=0;i<leng;i++){ String fname = list.get(i); File file = new File(fname); StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"upload_file"+i+"\";filename=\""+ file.getName() + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] data = sb.toString().getBytes(); out.write(data); DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } out.write("\r\n".getBytes()); //多个文件时,二个文件之间加入这个 in.close(); } out.write(end_data); out.flush(); out.close(); // 定义BufferedReader输入流来读取URL的响应 BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (Exception e) { System.out.println("发送POST请求出现异常!" + e); e.printStackTrace(); } }