1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
public static String (String urlPath, String content, int connectTimeout, int readTimeout, String reqCharset,String respCharset) throws Exception { try { URL url = new URL(urlPath); URLConnection urlConnection = url.openConnection(); System.setProperty("sun.net.client.defaultConnectTimeout", connectTimeout + ""); System.setProperty("sun.net.client.defaultReadTimeout", readTimeout + ""); urlConnection.setRequestProperty("Content-Type", "text/plain;charset=" + reqCharset); HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection; httpUrlConnection.setDoOutput(true); httpUrlConnection.setDoInput(true); httpUrlConnection.setUseCaches(false); httpUrlConnection.setRequestMethod("POST"); System.out.println("http开始连接"); httpUrlConnection.connect(); System.out.println("http已连接"); OutputStream outStrm = httpUrlConnection.getOutputStream(); outStrm.write(content.getBytes(reqCharset)); outStrm.flush(); outStrm.close(); int resultCode = httpUrlConnection.getResponseCode(); if (HttpURLConnection.HTTP_OK == resultCode) { System.out.println("HTTP_OK"); InputStream in = urlConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, respCharset)); StringBuffer temp = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { temp.append(line).append("rn"); } bufferedReader.close(); return temp.toString(); } else { throw new RuntimeException("调用接口失败!HTTP状态:" + resultCode); } } catch (Exception e) { throw new RuntimeException(e); } }
|
近期评论