List of usage examples for java.net HttpURLConnection setDoInput
public void setDoInput(boolean doinput)
From source file:com.example.ronald.tracle.RegistrationIntentService.java
private String downloadContent(String myurl) throws IOException { InputStream is = null;/*from ww w .j a va 2 s.c om*/ int length = 500; try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); int response = conn.getResponseCode(); Log.d(TAG, "The response is: " + response); is = conn.getInputStream(); // Convert the InputStream into a string String contentAsString = convertInputStreamToString(is, length); return contentAsString; } finally { if (is != null) { is.close(); } } }
From source file:org.fabric3.admin.interpreter.communication.DomainConnectionImpl.java
private HttpURLConnection createAddressConnection(String address, String path, String verb) throws CommunicationException { try {//from w w w . ja va 2 s. c om URL url = createUrl(address + path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod(verb); connection.setRequestProperty("Content-type", "application/json"); connection.setReadTimeout(TIMEOUT); setBasicAuth(connection); if (connection instanceof HttpsURLConnection) { HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; setSocketFactory(httpsConnection); } return connection; } catch (IOException e) { throw new CommunicationException(e); } }
From source file:com.pixem.core.activity.Example.java
/** Called when the activity is first created. */ @Override//from ww w . j a va2 s. co m public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (APP_ID == null) { Util.showAlert(this, "Warning", "Facebook Applicaton ID must be " + "specified before running this example: see Example.java"); } setContentView(R.layout.facebook); mLoginButton = (LoginButton) findViewById(R.id.login); mText = (TextView) Example.this.findViewById(R.id.txt); mRequestButton = (Button) findViewById(R.id.requestButton); mPostButton = (Button) findViewById(R.id.postButton); mDeleteButton = (Button) findViewById(R.id.deletePostButton); mUploadButton = (Button) findViewById(R.id.uploadButton); mFacebook = new Facebook(APP_ID); mAsyncRunner = new AsyncFacebookRunner(mFacebook); SessionStore.restore(mFacebook, this); SessionEvents.addAuthListener(new SampleAuthListener()); SessionEvents.addLogoutListener(new SampleLogoutListener()); mLoginButton.init(this, mFacebook); mRequestButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mAsyncRunner.request("me", new SampleRequestListener()); } }); mRequestButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE); mUploadButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Bundle params = new Bundle(); params.putString("method", "photos.upload"); URL uploadFileUrl = null; try { uploadFileUrl = new URL("http://www.facebook.com/images/devsite/iphone_connect_btn.jpg"); } catch (MalformedURLException e) { e.printStackTrace(); } try { HttpURLConnection conn = (HttpURLConnection) uploadFileUrl.openConnection(); conn.setDoInput(true); conn.connect(); int length = conn.getContentLength(); byte[] imgData = new byte[length]; InputStream is = conn.getInputStream(); is.read(imgData); params.putByteArray("picture", imgData); } catch (IOException e) { e.printStackTrace(); } mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null); } }); mUploadButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE); mPostButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mFacebook.dialog(Example.this, "feed", new SampleDialogListener()); } }); mPostButton.setVisibility(mFacebook.isSessionValid() ? View.VISIBLE : View.INVISIBLE); }
From source file:be.wimsymons.intellij.polopolyimport.PPImporter.java
private void postData(final String name, final Reader reader, final String contentType, final String extraParams) throws IOException { Writer writer = null;// w ww. j av a 2 s .co m LOGGER.info("Doing HTTP POST for " + name); try { URL httpURL = buildURL(target, extraParams); HttpURLConnection httpConnection = (HttpURLConnection) httpURL.openConnection(); httpConnection.setDoInput(true); httpConnection.setDoOutput(true); httpConnection.setUseCaches(false); httpConnection.setRequestMethod("PUT"); httpConnection.setRequestProperty("Content-Type", contentType); httpConnection.setConnectTimeout(2000); httpConnection.setReadTimeout(60000); httpConnection.connect(); if (contentType.contains("UTF-8")) { copyAndFlush(reader, httpConnection.getOutputStream()); } else { writer = new OutputStreamWriter(httpConnection.getOutputStream()); CharStreams.copy(reader, writer); writer.flush(); } int responseCode = httpConnection.getResponseCode(); String responseMessage = httpConnection.getResponseMessage(); if (responseCode < 200 || responseCode >= 300) { failureCount++; PPImportPlugin.doNotify("Import of " + name + " failed: " + responseCode + " - " + responseMessage + "\nCheck the server log for more details.", NotificationType.ERROR); } else { successCount++; } } catch (IOException e) { failureCount++; PPImportPlugin.doNotify("Import of " + name + " failed: " + e.getMessage(), NotificationType.ERROR); } finally { Closeables.close(reader, true); Closeables.close(writer, true); } }
From source file:com.wyp.module.controller.LicenseController.java
/** * wslicense//from www . j a v a2s.com * * @param properties * @return */ private String getCitrixLicense(String requestJson) { String licenses = ""; OutputStreamWriter out = null; InputStream is = null; long start = System.currentTimeMillis(); try { // ws url URL url = new URL(map.get("address")); // ws connection HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", " application/json"); connection.setRequestMethod("POST"); connection.connect(); out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); out.append(requestJson); out.flush(); // response string is = connection.getInputStream(); int length = is.available(); if (0 < length) { long end = System.currentTimeMillis(); System.out.println("?" + (end - start)); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuilder tempStr = new StringBuilder(); String temp = ""; while ((temp = reader.readLine()) != null) { tempStr.append(temp); } licenses = tempStr.toString(); // utf-8? System.out.println(licenses); } } catch (IOException e) { String eMsg = e.getMessage(); if ("Read timed out".equals(eMsg) || "Connection timed out: connect".equals(eMsg) || "Software caused connection abort: recv failed".equals(eMsg)) { long end = System.currentTimeMillis(); System.out.println(eMsg + (end - start)); licenses = "TIMEOUT"; } e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (is != null) { is.close(); } } catch (IOException ex) { ex.printStackTrace(); } } System.out.println(licenses); return licenses; }
From source file:net.phalapi.sdk.PhalApiClient.java
protected String doRequest(String requestUrl, Map<String, String> params, int timeoutMs) throws Exception { String result = null;// www . j ava 2 s.c o m URL url = null; HttpURLConnection connection = null; InputStreamReader in = null; url = new URL(requestUrl); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); // ? connection.setUseCaches(false); connection.setConnectTimeout(timeoutMs); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); //POST? String postContent = ""; Iterator<Entry<String, String>> iter = params.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next(); postContent += "&" + entry.getKey() + "=" + entry.getValue(); } out.writeBytes(postContent); out.flush(); out.close(); Log.d("[PhalApiClient requestUrl]", requestUrl + postContent); in = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(in); StringBuffer strBuffer = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { strBuffer.append(line); } result = strBuffer.toString(); Log.d("[PhalApiClient apiResult]", result); if (connection != null) { connection.disconnect(); } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }
From source file:com.example.rtobase2.AppEngineClient.java
public static Response getOrPost(Request request) { mErrorMessage = null;//ww w .ja v a 2 s . c o m 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 PUT) { byte[] payload = ((PUT) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("PUT"); 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(); } 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) { 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.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// ww w . j a va2s . c o m * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ @SuppressWarnings("deprecation") 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) { 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:de.uni.stuttgart.informatik.ToureNPlaner.Net.Handler.SyncCoreLoader.java
private long getLastModifiedOnServer() throws IOException { HttpURLConnection con = null; long result = new Date().getTime(); try {// w w w . j a v a 2 s .com URL url = new URL(coreURL + pathPrefix + corePrefix + coreLevel + coreSuffix); con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("HEAD"); con.setDoInput(true); con.setAllowUserInteraction(false); result = con.getHeaderFieldDate("Last-Modified", result); Log.d(TAG, "Last modified is parsed " + new Date(result)); } catch (MalformedURLException e) { e.printStackTrace(); return result; } finally { if (con != null) { con.disconnect(); } } return result; }
From source file:com.bpd.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// ww w . j a v a2 s .co 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; // Try to get filename key String filename = params.getString("filename"); // If found if (filename != null) { // Remove from params params.remove("filename"); } 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.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=\"" + ((filename != null) ? 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; }