List of usage examples for java.net HttpURLConnection addRequestProperty
public void addRequestProperty(String key, String value)
From source file:com.yahoo.sql4d.sql4ddriver.DDataSource.java
/** * For firing simple queries(i.e non join queries). * @param jsonQuery//from w ww. j a v a 2s . c om * @param print * @return */ private Either<String, Either<Mapper4All, JSONArray>> fireQuery(String jsonQuery, boolean requiresMapping) { StringBuilder buff = new StringBuilder(); try { URL url = null; try { url = new URL(String.format(brokerUrl, brokerHost, brokerPort)); } catch (MalformedURLException ex) { Logger.getLogger(DDataSource.class.getName()).log(Level.SEVERE, null, ex); return new Left<>("Bad Url : " + ex); } Proxy proxy = Proxy.NO_PROXY; if (proxyHost != null) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); } HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(proxy); httpConnection.setRequestMethod("POST"); httpConnection.addRequestProperty("content-type", "application/json"); httpConnection.setDoOutput(true); httpConnection.getOutputStream().write(jsonQuery.getBytes()); if (httpConnection.getResponseCode() == 500 || httpConnection.getResponseCode() == 404) { return new Left<>(String.format("Http %d : %s \n", httpConnection.getResponseCode(), httpConnection.getResponseMessage())); } BufferedReader stdInput = new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); String line = null; while ((line = stdInput.readLine()) != null) { buff.append(line); } } catch (IOException ex) { Logger.getLogger(DDataSource.class.getName()).log(Level.SEVERE, null, ex); } JSONArray possibleResArray = null; try { possibleResArray = new JSONArray(buff.toString()); } catch (JSONException je) { return new Left<>(String.format("Recieved data %s not in json format. \n", buff.toString())); } if (requiresMapping) { return new Right<String, Either<Mapper4All, JSONArray>>( new Left<Mapper4All, JSONArray>(new Mapper4All(possibleResArray))); } return new Right<String, Either<Mapper4All, JSONArray>>(new Right<Mapper4All, JSONArray>(possibleResArray)); }
From source file:com.vimc.ahttp.HurlWorker.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private void addBodyIfExists(HttpURLConnection connection, Request request) throws IOException { if (request.containsMutilpartData()) { connection.setDoOutput(true);/*from ww w. j a v a 2 s. c o m*/ connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); if (request.getStringParams().size() > 0) { writeStringFields(request.getStringParams(), out, request.getBoundray()); } if (request.getFileParams().size() > 0) { writeFiles(request.getFileParams(), out, request.getBoundray()); } if (request.getByteParams().size() > 0) { writeBytes(request.getByteParams(), out, request.getBoundray()); } out.flush(); out.close(); } else { byte[] body = request.getStringBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.flush(); out.close(); } } }
From source file:org.apache.jmeter.protocol.http.control.TestHTTPMirrorThread.java
public void testSleep() throws Exception { URL url = new URL("http", "localhost", HTTP_SERVER_PORT, "/"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.addRequestProperty("X-Sleep", "1000"); conn.connect();//from www . j a va2 s. com // use nanoTime to do timing measurement or calculation // See https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks long now = System.nanoTime(); final InputStream inputStream = conn.getInputStream(); while (inputStream.read() != -1) { } inputStream.close(); final long elapsed = (System.nanoTime() - now) / 1000000L; assertTrue("Expected > 1000 " + elapsed, elapsed >= 1000); }
From source file:com.yahoo.sql4d.sql4ddriver.DDataSource.java
/** * All commands./*from w w w.j a v a 2 s . c om*/ * @return */ private Either<String, Either<JSONArray, JSONObject>> fireCommand(String endPoint, String optData, String httpType) { StringBuilder buff = new StringBuilder(); try { URL url = null; try { url = new URL(String.format(coordinatorUrl + endPoint, coordinatorHost, coordinatorPort)); } catch (MalformedURLException ex) { Logger.getLogger(DDataSource.class.getName()).log(Level.SEVERE, null, ex); return new Left<>("Bad Url : " + ex); } Proxy proxy = Proxy.NO_PROXY; if (proxyHost != null) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); } HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(proxy); httpConnection.setRequestMethod(httpType); httpConnection.addRequestProperty("content-type", "application/json"); httpConnection.setDoOutput(true); if ("POST".equals(httpType) && optData != null) { httpConnection.getOutputStream().write(optData.getBytes()); } if (httpConnection.getResponseCode() == 500 || httpConnection.getResponseCode() == 404) { return new Left<>(String.format("Http %d : %s \n", httpConnection.getResponseCode(), httpConnection.getResponseMessage())); } BufferedReader stdInput = new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); String line = null; while ((line = stdInput.readLine()) != null) { buff.append(line); } } catch (IOException ex) { Logger.getLogger(DDataSource.class.getName()).log(Level.SEVERE, null, ex); } JSONArray possibleResArray = null; try { possibleResArray = new JSONArray(buff.toString()); return new Right<String, Either<JSONArray, JSONObject>>( new Left<JSONArray, JSONObject>(possibleResArray)); } catch (JSONException je) { try { JSONObject possibleResObj = new JSONObject(buff.toString()); return new Right<String, Either<JSONArray, JSONObject>>( new Right<JSONArray, JSONObject>(possibleResObj)); } catch (JSONException je2) { return new Left<>(String.format("Recieved data %s not in json format. \n", buff.toString())); } } }
From source file:com.psbk.modulperwalian.Controller.DosenController.java
public List<Mahasiswa> getMhsPerwalian() throws Exception { mhsList = new ArrayList<>(); String url = "dosen/x/dos01"; obj = new URL(BASE_URL + url); HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "application/json"); connection.addRequestProperty("Authorization", "Basic YWRtaW46YWRtaW4="); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine;/*from ww w . j a v a 2 s . com*/ StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject result; JSONObject jsonObject = new JSONObject(response.toString()); JSONArray jsonArray = (JSONArray) jsonObject.get("result"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject objek = (JSONObject) jsonArray.get(i); result = (JSONObject) objek.get("map"); Mahasiswa s = new Mahasiswa(); s.setNrp(result.getString("nrp")); s.setNama(result.getString("nama")); mhsList.add(s); } return mhsList; }
From source file:com.psbk.modulperwalian.Controller.DosenController.java
public Dosen getDataDosen() throws Exception { FacesContext fc = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest(); String nrp = request.getParameter("user"); // System.out.println(nrp); mhsList = new ArrayList<>(); String url = "dosen/getDosen/dos02"; obj = new URL(BASE_URL + url); HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "application/json"); connection.addRequestProperty("Authorization", "Basic YWRtaW46YWRtaW4="); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine;// w w w . j a v a 2s. co m StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject result; JSONObject jsonObject = new JSONObject(response.toString()); result = (JSONObject) jsonObject.get("result"); result = (JSONObject) result.get("map"); Dosen dosen = new Dosen(); dosen.setIdDosen(result.getString("id_dosen")); dosen.setNama(result.getString("nama_dosen")); dosen.setTgl(result.getString("tglLahir")); dosen.setTelp(result.getString("noTelp")); return dosen; }
From source file:org.orbisgis.core.layerModel.mapcatalog.Workspace.java
/** * Add a mapcontext to the workspace//from w ww . j av a 2s . c om * @param mapContext * @return The ID of the published map context * @throws IOException */ public int publishMapContext(MapContext mapContext, Integer mapContextId) throws IOException { // Construct request URL requestWorkspacesURL; if (mapContextId == null) { // Post a new map context requestWorkspacesURL = new URL(RemoteCommons.getUrlPostContext(cParams, workspaceName)); } else { // Update an existing map context requestWorkspacesURL = new URL(RemoteCommons.getUrlUpdateContext(cParams, workspaceName, mapContextId)); } // Establish connection HttpURLConnection connection = (HttpURLConnection) requestWorkspacesURL.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setConnectTimeout(cParams.getConnectionTimeOut()); connection.addRequestProperty("Content-Type", "text/xml"); OutputStream out = connection.getOutputStream(); mapContext.write(out); // Send map context out.close(); // Get response int responseCode = connection.getResponseCode(); if (!((responseCode == HttpURLConnection.HTTP_CREATED && mapContextId == null) || (responseCode == HttpURLConnection.HTTP_OK && mapContextId != null))) { throw new IOException(I18N.tr("HTTP Error {0} message : {1} with the URL {2}", connection.getResponseCode(), connection.getResponseMessage(), requestWorkspacesURL)); } if (mapContextId == null) { // Get response content BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), RemoteCommons.getConnectionCharset(connection))); XMLInputFactory factory = XMLInputFactory.newInstance(); // Parse Data XMLStreamReader parser; try { parser = factory.createXMLStreamReader(in); // Fill workspaces int resId = parsePublishResponse(parser); parser.close(); return resId; } catch (XMLStreamException ex) { throw new IOException(I18N.tr("Invalid XML content"), ex); } } else { return mapContextId; } }
From source file:org.droidparts.http.worker.HttpURLConnectionWorker.java
public HttpURLConnection getConnection(String urlStr, String requestMethod) throws HTTPException { try {/*from w w w. j a v a 2 s .c om*/ URL url = new URL(urlStr); HttpURLConnection conn; if (proxy != null) { conn = (HttpURLConnection) url.openConnection(proxy); } else { conn = (HttpURLConnection) url.openConnection(); } for (String key : headers.keySet()) { for (String val : headers.get(key)) { conn.addRequestProperty(key, val); } } conn.setRequestProperty("http.agent", userAgent); conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); conn.setRequestProperty("Connection", "Keep-Alive"); setupBasicAuth(); conn.setRequestMethod(requestMethod); if (PUT.equals(requestMethod) || POST.equals(requestMethod)) { conn.setDoOutput(true); } return conn; } catch (Exception e) { throw new HTTPException(e); } }
From source file:com.psbk.modulperwalian.Controller.DosenController.java
public String getDataDosenTest() throws Exception { String nip = null;/*from w ww .ja v a2s . c om*/ URL url = new URL(BASE_URL + "dosen/apa/"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.addRequestProperty("Authorization", "Basic YWRtaW46YWRtaW4="); String input = "{\"id_dosen\"dos02\"}"; OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { nip = output; } return output; }
From source file:foam.dao.HTTPSink.java
@Override public void put(Object obj, Detachable sub) { HttpURLConnection conn = null; OutputStream os = null;/* ww w . j a va 2 s .c o m*/ BufferedWriter writer = null; try { Outputter outputter = null; conn = (HttpURLConnection) new URL(url_).openConnection(); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); if (format_ == Format.JSON) { outputter = new foam.lib.json.Outputter(OutputterMode.NETWORK); conn.addRequestProperty("Accept", "application/json"); conn.addRequestProperty("Content-Type", "application/json"); } else if (format_ == Format.XML) { // TODO: make XML Outputter conn.addRequestProperty("Accept", "application/xml"); conn.addRequestProperty("Content-Type", "application/xml"); } conn.connect(); os = conn.getOutputStream(); writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8)); writer.write(outputter.stringify((FObject) obj)); writer.flush(); writer.close(); os.close(); // check response code int code = conn.getResponseCode(); if (code != HttpServletResponse.SC_OK) { throw new RuntimeException("Http server did not return 200."); } } catch (Throwable t) { throw new RuntimeException(t); } finally { IOUtils.closeQuietly(writer); IOUtils.closeQuietly(os); if (conn != null) { conn.disconnect(); } } }