List of usage examples for java.net HttpURLConnection setDoInput
public void setDoInput(boolean doinput)
From source file:org.fabric3.admin.interpreter.communication.DomainConnectionImpl.java
public HttpURLConnection put(String path, URL resource) throws CommunicationException { try {/* www . j ava 2 s .c o m*/ URL url = createUrl(addresses.getLast() + path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setChunkedStreamingMode(4096); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("PUT"); connection.setRequestProperty("Content-type", "application/json"); setBasicAuth(connection); if (connection instanceof HttpsURLConnection) { HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; setSocketFactory(httpsConnection); } InputStream is = null; OutputStream os = null; try { os = connection.getOutputStream(); is = resource.openStream(); copy(is, os); os.flush(); } finally { if (os != null) { os.close(); } if (is != null) { is.close(); } } return connection; } catch (IOException e) { throw new CommunicationException(e); } }
From source file:com.zlk.bigdemo.android.volley.toolbox.HurlStack.java
/** * Opens an {@link HttpURLConnection} with parameters. * @param url/* ww w . jav a 2s. c o m*/ * @return an open connection * @throws IOException */ private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException { HttpURLConnection connection = createConnection(url); int timeoutMs = request.getTimeoutMs(); connection.setConnectTimeout(timeoutMs); connection.setReadTimeout(timeoutMs); connection.setUseCaches(false); connection.setDoInput(true); // use caller-provided custom SslSocketFactory, if any, for HTTPS if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory); } return connection; }
From source file:com.permpings.utils.facebook.sdk.Util.java
/** * Connect to an HTTP URL and return the response as a string. * * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url - the resource to open: must be a welformed URL * @param method - the HTTP method to use ("GET", "POST", etc.) * @param params - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String// w w w .ja v a 2s .c o m * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Util.logd("Facebook-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { Object parameter = params.get(key); if (parameter instanceof byte[]) { dataparams.putByteArray(key, (byte[]) parameter); } } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:com.ble.facebook.Util.java
public static String posttowall(String url, String method, Bundle params, String Accesstoken) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os;/* www . j a va2 s . c om*/ if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Log.d("Facebook-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } } // use method override if (!params.containsKey("method")) { params.putByteArray("method", method.getBytes()); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(Accesstoken); params.putByteArray("access_token", decoded_token.getBytes()); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); Log.d("OutputStreamedData", ("--" + strBoundary + endLine) + (encodePostBody(params, strBoundary)) + (endLine + "--" + strBoundary + endLine)); os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:karroo.app.test.facebook.Util.java
/** * Connect to an HTTP URL and return the response as a string. * * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url - the resource to open: must be a welformed URL * @param method - the HTTP method to use ("GET", "POST", etc.) * @param params - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String/*from w ww . j a v a2 s . c o m*/ * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Log.d("Facebook-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { // if (params.getByteArray(key) != null) { if (params.get(key) instanceof byte[]) { dataparams.putByteArray(key, params.getByteArray(key)); } } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:com.mobli.android.Util.java
/** * Connect to an HTTP URL and return the response as a string. * //from www . j av a 2 s . c o m * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url * - the resource to open: must be a welformed URL * @param method * - the HTTP method to use ("GET", "POST", etc.) * @param params * - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException * - if the URL format is invalid * @throws IOException * - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Util.logd("Mobli-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " MobliAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { Object parameter = params.get(key); if (parameter instanceof byte[]) { dataparams.putByteArray(key, (byte[]) parameter); } } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a Mobli error response = read(conn.getErrorStream()); } return response; }
From source file:com.geocent.owf.openlayers.DataRequestProxy.java
/** * Gets the data from the provided remote URL. * Note that the data will be returned from the method and not automatically * populated into the response object./*from w w w . j a v a2s.c om*/ * * @param request ServletRequest object containing the request data. * @param response ServletResponse object for the response information. * @param url URL from which the data will be retrieved. * @return Data from the provided remote URL. * @throws IOException */ public String getData(HttpServletRequest request, HttpServletResponse response, String url) throws IOException { if (!allowUrl(url)) { throw new UnknownHostException("Request to invalid host not allowed."); } HttpURLConnection connection = (HttpURLConnection) (new URL(url).openConnection()); connection.setRequestMethod(request.getMethod()); // Detects a request with a payload inside the message body if (request.getContentLength() > 0) { connection.setRequestProperty("Content-Type", request.getContentType()); connection.setDoOutput(true); connection.setDoInput(true); byte[] requestPayload = IOUtils.toByteArray(request.getInputStream()); connection.getOutputStream().write(requestPayload); connection.getOutputStream().flush(); } // Create handler for the given content type and proxy the extracted information Handler contentHandler = HandlerFactory.getHandler(connection.getContentType()); return contentHandler.handleContent(response, connection.getInputStream()); }
From source file:de.sebastianrothbucher.vaadin.meetup.userauth.MeetupUserAuthentication.java
JSONObject curl(String method, String url, Map<String, String> headers, String data) throws TechnicalException { // very simple, low load only ;-) HttpURLConnection connection = null; OutputStream connectionOut = null; InputStream connectionIn = null; try {// w w w . ja va 2 s . co m connection = (HttpURLConnection) ((new URL(url)).openConnection()); connection.setDoInput(true); connection.setDoOutput(data != null); connection.setRequestMethod(method); for (String header : headers.keySet()) { connection.addRequestProperty(header, headers.get(header)); } connection.connect(); if (data != null) { connectionOut = connection.getOutputStream(); connectionOut.write(data.getBytes("UTF-8")); connectionOut.flush(); } connectionIn = connection.getInputStream(); BufferedReader buffRead = new BufferedReader(new InputStreamReader(connectionIn)); String jsonString = ""; String line = buffRead.readLine(); while (line != null) { jsonString += line; line = buffRead.readLine(); } JSONObject jsonObj = new JSONObject(jsonString); return jsonObj; } catch (ProtocolException e) { throw new TechnicalException(e); } catch (MalformedURLException e) { throw new TechnicalException(e); } catch (IOException e) { throw new TechnicalException(e); } catch (JSONException e) { throw new TechnicalException(e); } finally { if (connectionOut != null) { try { connectionOut.close(); } catch (Exception exc) { // best effort } } if (connectionIn != null) { try { connectionIn.close(); } catch (Exception exc) { // best effort } } if (connection != null) { try { connection.disconnect(); } catch (Exception exc) { // best effort } } } }
From source file:com.orange.labs.sdk.RestUtils.java
public void uploadRequest(URL url, File file, String folderIdentifier, final Map<String, String> headers, final OrangeListener.Success<JSONObject> success, final OrangeListener.Progress progress, final OrangeListener.Error failure) { // open a URL connection to the Server FileInputStream fileInputStream = null; try {/*w w w . j av a2 s .c om*/ fileInputStream = new FileInputStream(file); // Open a HTTP connection to the URL HttpURLConnection conn = (HttpsURLConnection) url.openConnection(); // Allow Inputs & Outputs conn.setDoInput(true); conn.setDoOutput(true); // Don't use a Cached Copy conn.setUseCaches(false); conn.setRequestMethod("POST"); // // Define headers // // Create an unique boundary String boundary = "UploadBoundary"; conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); for (String key : headers.keySet()) { conn.setRequestProperty(key.toString(), headers.get(key)); } // // Write body part // DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); int bytesAvailable = fileInputStream.available(); String marker = "\r\n--" + boundary + "\r\n"; dos.writeBytes(marker); dos.writeBytes("Content-Disposition: form-data; name=\"description\"\r\n\r\n"); // Create JSonObject : JSONObject params = new JSONObject(); params.put("name", file.getName()); params.put("size", String.valueOf(bytesAvailable)); params.put("folder", folderIdentifier); dos.writeBytes(params.toString()); dos.writeBytes(marker); dos.writeBytes( "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n"); dos.writeBytes("Content-Type: image/jpeg\r\n\r\n"); int progressValue = 0; int bytesRead = 0; byte buf[] = new byte[1024]; BufferedInputStream bufInput = new BufferedInputStream(fileInputStream); while ((bytesRead = bufInput.read(buf)) != -1) { // write output dos.write(buf, 0, bytesRead); dos.flush(); progressValue += bytesRead; // update progress bar progress.onProgress((float) progressValue / bytesAvailable); } dos.writeBytes(marker); // // Responses from the server (code and message) // int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); // close streams fileInputStream.close(); dos.flush(); dos.close(); if (serverResponseCode == 200 || serverResponseCode == 201) { BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = ""; String line; while ((line = rd.readLine()) != null) { Log.i("FileUpload", "Response: " + line); response += line; } rd.close(); JSONObject object = new JSONObject(response); success.onResponse(object); } else { BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getErrorStream())); String response = ""; String line; while ((line = rd.readLine()) != null) { Log.i("FileUpload", "Error: " + line); response += line; } rd.close(); JSONObject errorResponse = new JSONObject(response); failure.onErrorResponse(new CloudAPIException(serverResponseCode, errorResponse)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:TaxSvc.TaxSvc.java
public CancelTaxResult CancelTax(CancelTaxRequest req) { //Create URL/*from w w w . j a v a2 s . co m*/ String taxget = svcURL + "/1.0/tax/cancel"; URL url; HttpURLConnection conn; try { //Connect to URL with authorization header, request content. url = new URL(taxget); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content conn.setRequestProperty("Authorization", encoded); //Add authorization header conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); //Tells the serializer to only include those parameters that are not null String content = mapper.writeValueAsString(req); //System.out.println(content); //Uncomment to see the content of the request object conn.setRequestProperty("Content-Length", Integer.toString(content.length())); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(content); wr.flush(); wr.close(); conn.disconnect(); if (conn.getResponseCode() != 200) //Note: tax/cancel will return a 200 response even if the document could not be cancelled. Special attention needs to be paid to the ResultCode. { //If we got a more serious error, print out the error message. CancelTaxResult res = mapper.readValue(conn.getErrorStream(), CancelTaxResult.class); //Deserialize response return res; } else { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); CancelTaxResponse res = mapper.readValue(conn.getInputStream(), CancelTaxResponse.class); //Deserialize response return res.CancelTaxResult; } } catch (IOException e) { e.printStackTrace(); return null; } }