import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Map;public class HttpUtils { /* * 打开链接,确定连接; * */ public static HttpURLConnection conn(String path,String method) throws IOException{ URL url = new URL(path); HttpURLConnection con = (HttpURLConnection)url.openConnection();//打开连接 con.setRequestMethod(method); con.setConnectTimeout(50000); con.setDoOutput(true); con.setDoInput(true); con.setRequestProperty("apikey", "db3c2b8c6a66509b6ee353d2dc09eea1"); con.connect(); if(con.getResponseCode()==200){ return con; } return null; } /* * get或post请求获取服务器图片 * */ public static File connImg(String path,String method) throws IOException{ File file = new File(""+new SimpleDateFormat("yyyyMMdd").format(new Date().getTime())); File f = new File(file,""+new Date().getTime()+"."+path.substring(path.lastIndexOf(".")+1)); if(!file.exists()){ file.mkdirs(); } if(conn(path,method) instanceof HttpURLConnection){ HttpURLConnection con = conn(path,method); InputStream is = con.getInputStream(); FileOutputStream fos = new FileOutputStream(f); byte[] b = new byte[1024]; int l = is.read(b); while(l!=-1){ fos.write(b, 0, l); l = is.read(b); } is.close(); fos.close(); } return f; } /* * get或post抓取服务器数据 * */ public static String connData(String path,String method) throws IOException{ String str=null; if(conn(path,method) instanceof HttpURLConnection){ HttpURLConnection con = conn(path,method); InputStream is = con.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int l = is.read(b); while(l!=-1){ baos.write(b, 0, l); l = is.read(b); } str = new String(baos.toByteArray(),"UTF-8"); } return str; } /* * get或post提交数据并接受服务器的返回值 * */ public static String connRequest(String path,String method,Mappara) throws IOException{ String s=null; StringBuilder sb = new StringBuilder(); for(Map.Entry me:para.entrySet()){ sb.append(me.getKey()+"="+URLEncoder.encode(me.getValue(),"UTF-8")+"&"); } sb.deleteCharAt(sb.length()-1); path=path+"?"+sb; if(conn(path,method) instanceof HttpURLConnection){ HttpURLConnection con = conn(path,method); InputStream is = con.getInputStream(); byte[] b = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int l = is.read(b); while(l!=-1){ baos.write(b, 0, l); l=is.read(b); } s = new String(baos.toByteArray(),"UTF-8"); } return s; }}