List of usage examples for java.net HttpURLConnection setDoInput
public void setDoInput(boolean doinput)
From source file:net.sbbi.upnp.messages.StateVariableMessage.java
/** * Executes the state variable query and retuns the UPNP device response, according to the UPNP specs, * this method could take up to 30 secs to process ( time allowed for a device to respond to a request ) * @return a state variable response object containing the variable value * @throws IOException if some IOException occurs during message send and reception process * @throws UPNPResponseException if an UPNP error message is returned from the server * or if some parsing exception occurs ( detailErrorCode = 899, detailErrorDescription = SAXException message ) *///from w w w . ja v a 2 s .c om public StateVariableResponse service() throws IOException, UPNPResponseException { StateVariableResponse rtrVal = null; UPNPResponseException upnpEx = null; IOException ioEx = null; StringBuffer body = new StringBuffer(256); body.append("<?xml version=\"1.0\"?>\r\n"); body.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\""); body.append(" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"); body.append("<s:Body>"); body.append("<u:QueryStateVariable xmlns:u=\"urn:schemas-upnp-org:control-1-0\">"); body.append("<u:varName>").append(serviceStateVar.getName()).append("</u:varName>"); body.append("</u:QueryStateVariable>"); body.append("</s:Body>"); body.append("</s:Envelope>"); if (log.isDebugEnabled()) log.debug("POST prepared for URL " + service.getControlURL()); URL url = new URL(service.getControlURL().toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); HttpURLConnection.setFollowRedirects(false); //conn.setConnectTimeout( 30000 ); conn.setRequestProperty("HOST", url.getHost() + ":" + url.getPort()); conn.setRequestProperty("SOAPACTION", "\"urn:schemas-upnp-org:control-1-0#QueryStateVariable\""); conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\""); conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length())); OutputStream out = conn.getOutputStream(); out.write(body.toString().getBytes()); out.flush(); conn.connect(); InputStream input = null; if (log.isDebugEnabled()) log.debug("executing query :\n" + body); try { input = conn.getInputStream(); } catch (IOException ex) { // java can throw an exception if he error code is 500 or 404 or something else than 200 // but the device sends 500 error message with content that is required // this content is accessible with the getErrorStream input = conn.getErrorStream(); } if (input != null) { int response = conn.getResponseCode(); String responseBody = getResponseBody(input); if (log.isDebugEnabled()) log.debug("received response :\n" + responseBody); SAXParserFactory saxParFact = SAXParserFactory.newInstance(); saxParFact.setValidating(false); saxParFact.setNamespaceAware(true); StateVariableResponseParser msgParser = new StateVariableResponseParser(serviceStateVar); StringReader stringReader = new StringReader(responseBody); InputSource src = new InputSource(stringReader); try { SAXParser parser = saxParFact.newSAXParser(); parser.parse(src, msgParser); } catch (ParserConfigurationException confEx) { // should never happen // we throw a runtimeException to notify the env problem throw new RuntimeException( "ParserConfigurationException during SAX parser creation, please check your env settings:" + confEx.getMessage()); } catch (SAXException saxEx) { // kind of tricky but better than nothing.. upnpEx = new UPNPResponseException(899, saxEx.getMessage()); } finally { try { input.close(); } catch (IOException ex) { // ignoring } } if (upnpEx == null) { if (response == HttpURLConnection.HTTP_OK) { rtrVal = msgParser.getStateVariableResponse(); } else if (response == HttpURLConnection.HTTP_INTERNAL_ERROR) { upnpEx = msgParser.getUPNPResponseException(); } else { ioEx = new IOException("Unexpected server HTTP response:" + response); } } } try { out.close(); } catch (IOException ex) { // ignore } conn.disconnect(); if (upnpEx != null) { throw upnpEx; } if (rtrVal == null && ioEx == null) { ioEx = new IOException("Unable to receive a response from the UPNP device"); } if (ioEx != null) { throw ioEx; } return rtrVal; }
From source file:com.nimbits.user.GoogleAuthentication.java
private HttpURLConnection getConnection(final String service, final EmailAddress username, final String password) throws IOException { final URL url = new URL(Path.PATH_GOOGLE_CLIENT_LOGIN); final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true);/*from w w w . j a va2s .c o m*/ urlConnection.setUseCaches(false); urlConnection.setRequestProperty(Parameters.contentType.getText(), "application/x-www-form-urlencoded"); final StringBuilder content = new StringBuilder(); content.append("Email=").append(username.getValue()).append("&Passwd=").append(password).append("&service=") .append(service); final OutputStream outputStream = urlConnection.getOutputStream(); outputStream.write(content.toString().getBytes(Const.CONST_ENCODING)); outputStream.close(); return urlConnection; }
From source file:com.example.httpjson.AppEngineClient.java
public static Response getOrPost(Request request) { mErrorMessage = null;/*from w ww . j av a 2 s .c om*/ HttpURLConnection conn = null; Response response = null; try { conn = (HttpURLConnection) request.uri.openConnection(); // if (!mAuthenticator.authenticate(conn)) { // mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage(); // } else { if (request.headers != null) { for (String header : request.headers.keySet()) { for (String value : request.headers.get(header)) { conn.addRequestProperty(header, value); } } } if (request instanceof POST) { byte[] payload = ((POST) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); // ... OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); // conn.setFixedLengthStreamingMode(payload.length); // conn.getOutputStream().write(payload); int status = conn.getResponseCode(); if (status / 100 != 2) response = new Response(status, new Hashtable<String, List<String>>(), conn.getResponseMessage().getBytes()); } if (response == null) { int a = conn.getResponseCode(); if (a == 401) { response = new Response(a, conn.getHeaderFields(), new byte[] {}); } InputStream a1 = conn.getErrorStream(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); byte[] body = readStream(in); response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body); // List<String> a = conn.getHeaderFields().get("aa"); } } } catch (IOException e) { e.printStackTrace(System.err); mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": " + e.getLocalizedMessage(); } finally { if (conn != null) conn.disconnect(); } return response; }
From source file:com.eTilbudsavis.etasdk.network.impl.HttpURLNetwork.java
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(request.getTimeOut()); connection.setReadTimeout(request.getTimeOut()); connection.setUseCaches(false);/*from ww w .ja v a 2 s . c o m*/ connection.setDoInput(true); // use caller-provided custom SslSocketFactory, if any, for HTTPS // if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { // ((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory); // } return connection; }
From source file:com.windigo.http.client.HttpUrlConnectionClient.java
/** * Setup {@link HttpURLConnection} to remote url set some configuration and * body if exist/*from ww w.j a v a 2 s . co m*/ * * @param request * @throws MalformedURLException * @throws IOException */ private void setupHttpUrlConnectionClient(HttpURLConnection connection, Request request) throws MalformedURLException, IOException { connection.setDoInput(true); // set headers for request Logger.log("[Request] Found " + request.getHeaders().size() + " header"); addHeaders(request.getHeaders()); if (request.hasBody()) { // if its post request connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); bw.write(writeBodyParams(request.getBodyParams())); // clean up mess bw.flush(); bw.close(); os.close(); } }
From source file:foam.dao.HTTPSink.java
@Override public void put(Object obj, Detachable sub) { HttpURLConnection conn = null; OutputStream os = null;/*from ww w . j a va 2s. com*/ 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(); } } }
From source file:at.florian_lentsch.expirysync.net.JsonCaller.java
private void prepareConnection(HttpURLConnection connection, String method, boolean outputAvailable) throws ProtocolException { connection.setDoInput(true); connection.setDoOutput(outputAvailable); connection.setRequestMethod(method); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); // send cookies if previously set: if (this.cookieManager.getCookieStore().getCookies().size() > 0) { connection.setRequestProperty("Cookie", TextUtils.join(",", this.cookieManager.getCookieStore().getCookies())); }// w ww. j a v a 2 s .c o m }
From source file:com.snda.mymarket.providers.downloads.HurlStack.java
/** * Opens an {@link HttpURLConnection} with parameters. * @param url//from w w w . j a va 2s . co m * @return an open connection * @throws IOException */ private HttpURLConnection openConnection(URL url, HttpUriRequest request) throws IOException { HttpURLConnection connection = createConnection(url); int timeoutMs = TIMEOUT_MSECONDES; connection.setConnectTimeout(timeoutMs); connection.setReadTimeout(timeoutMs); connection.setUseCaches(false); connection.setDoInput(true); return connection; }
From source file:com.finlay.geomonsters.WeatherManager.java
private String getWeatherData(String address) { Log.v(TAG, "getWeatherData: " + address); HttpURLConnection con = null; InputStream is = null;// www.java 2 s . c o m try { con = (HttpURLConnection) (new java.net.URL(address)).openConnection(); con.setRequestMethod("GET"); con.setDoInput(true); con.setDoOutput(true); con.connect(); Log.v(TAG, "Open Weather connected."); _parent.appendMessage("Open Weather connected."); // Let's read the response StringBuffer buffer = new StringBuffer(); is = con.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = br.readLine()) != null) buffer.append(line + "\r\n"); is.close(); con.disconnect(); return buffer.toString(); } catch (Throwable t) { Log.e(TAG, t.getMessage()); } finally { try { is.close(); } catch (Throwable t) { } try { con.disconnect(); } catch (Throwable t) { } } return null; }
From source file:com.wareninja.android.commonutils.foursquareV2.http.AbstractHttpApi.java
public HttpURLConnection createHttpURLConnectionPost(URL url, String boundary) throws IOException { //-WareNinjaUtils.trustEveryone();//YG HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true);// w w w.j a va 2 s . c o m conn.setUseCaches(false); conn.setConnectTimeout(TIMEOUT * 1000); conn.setRequestMethod("POST"); conn.setRequestProperty(CLIENT_VERSION_HEADER, mClientVersion); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); return conn; }