// прочитать весь json в строку private static String readAll() throws IOException { StringBuilder data = new StringBuilder(); try { HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection())); con.setRequestMethod("GET"); con.setDoInput(true); String s; try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { while ((s = in.readLine()) != null) { data.append(s); } } } catch (MalformedURLException e) { e.printStackTrace(); throw new MalformedURLException("Url is not valid"); } catch (ProtocolException e) { e.printStackTrace(); throw new ProtocolException("No such protocol, it must be POST,GET,PATCH,DELETE etc."); } catch (IOException e) { e.printStackTrace(); throw new IOException("cannot read from server"); } return data.toString(); }
// добавить продукт в базу json server public static void add(ProductREST product) throws NotValidProductException, IOException { try { check(product); // рповеряем продукт // connection к серверу HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection())); con.setRequestMethod("POST"); // метод post для добавления // генерируем запрос StringBuilder urlParameters = new StringBuilder(); urlParameters .append("name=") .append(URLEncoder.encode(product.getName(), "UTF8")) .append("&"); urlParameters.append("price=").append(product.getPrice()).append("&"); urlParameters.append("weight=").append(product.getWeight()).append("&"); urlParameters .append("manufacturer=") .append(product.getManufacturer().getCountry()) .append("&"); urlParameters.append("category=").append(URLEncoder.encode(product.getCategory(), "UTF8")); con.setDoOutput(true); // разрешаем отправку данных // отправляем try (DataOutputStream out = new DataOutputStream(con.getOutputStream())) { out.writeBytes(urlParameters.toString()); } // код ответа int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + PRODUCT_URL); System.out.println("Response Code : " + responseCode); } catch (NotValidProductException e) { e.printStackTrace(); throw e; } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new UnsupportedEncodingException("cannot recognize encoding"); } catch (ProtocolException e) { e.printStackTrace(); throw new ProtocolException("No such protocol, protocol must be POST,DELETE,PATCH,GET etc."); } catch (MalformedURLException e) { e.printStackTrace(); throw new MalformedURLException("Url is not valid"); } catch (IOException e) { e.printStackTrace(); throw new IOException("cannot write information to server"); } }
public static String httpPost(String urlAddress, String[] params) { URL url = null; HttpURLConnection conn = null; BufferedReader in = null; StringBuffer sb = new StringBuffer(); try { url = new URL(urlAddress); conn = (HttpURLConnection) url.openConnection(); // 建立连接 // 设置通用的请求属性 /* * conn.setRequestProperty("user-agent", * "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); */ conn.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) "); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setUseCaches(false); conn.setDoInput(true); // conn.setConnectTimeout(5 * 1000); conn.setDoOutput(true); conn.setRequestMethod("POST"); String paramsTemp = ""; for (String param : params) { if (param != null && !"".equals(param)) { if (params.length > 1) { paramsTemp += "&" + param; } else if (params.length == 1) { paramsTemp = params[0]; } } } byte[] b = paramsTemp.getBytes(); System.out.println("btye length:" + b.length); // conn.setRequestProperty("Content-Length", // String.valueOf(b.length)); conn.getOutputStream().write(b, 0, b.length); conn.getOutputStream().flush(); conn.getOutputStream().close(); int count = conn.getResponseCode(); if (200 == count) { in = new BufferedReader(new InputStreamReader(conn.getInputStream())); // 发送请求 } else { System.out.println("错误类型:" + count); return "server no start-up"; } while (true) { String line = in.readLine(); if (line == null) { break; } else { sb.append(line); } } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { System.out.println("error ioexception:" + e.getMessage()); e.printStackTrace(); return "server no start-up"; } finally { try { if (in != null) { in.close(); } if (conn != null) { conn.disconnect(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return sb.toString(); }