List of usage examples for java.net HttpURLConnection setDoInput
public void setDoInput(boolean doinput)
From source file:com.juick.android.Utils.java
public static RESTResponse postJSON(final Context context, final String url, final String data, final String contentType) { final URLAuth authorizer = getAuthorizer(url); final RESTResponse[] ret = new RESTResponse[] { null }; final boolean[] cookieCleared = new boolean[] { false }; authorizer.authorize(context, false, false, url, new Function<Void, String>() { @Override//from www. ja v a 2s. c om public Void apply(String myCookie) { final boolean noAuthRequested = myCookie != null && myCookie.equals(URLAuth.REFUSED_AUTH); if (noAuthRequested) myCookie = null; HttpURLConnection conn = null; try { String nurl = authorizer.authorizeURL(url, myCookie); URL jsonURL = new URL(nurl); conn = (HttpURLConnection) jsonURL.openConnection(); if (contentType != null) { conn.addRequestProperty("Content-Type", contentType); } authorizer.authorizeRequest(context, conn, myCookie, nurl); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.close(); URLAuth.ReplyCode authReplyCode = authorizer.validateNon200Reply(conn, url, false); try { if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && noAuthRequested) { ret[0] = new RESTResponse(NO_AUTH, false, null); } else if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && !cookieCleared[0]) { cookieCleared[0] = true; // don't enter loop final Function<Void, String> thiz = this; authorizer.clearCookie(context, new Runnable() { @Override public void run() { authorizer.authorize(context, true, false, url, thiz); } }); } else { if (conn.getResponseCode() == 200 || authReplyCode == URLAuth.ReplyCode.NORMAL) { InputStream inputStream = conn.getInputStream(); ret[0] = streamToString(inputStream, null); inputStream.close(); } else { ret[0] = new RESTResponse( "HTTP " + conn.getResponseCode() + " " + conn.getResponseMessage(), false, null); } } } finally { conn.disconnect(); } } catch (Exception e) { Log.e("getJSON", e.toString()); ret[0] = new RESTResponse(ServerToClient.NETWORK_CONNECT_ERROR + e.toString(), true, null); } finally { if (conn != null) { conn.disconnect(); } } return null; //To change body of implemented methods use File | Settings | File Templates. } }); while (ret[0] == null) { // bad, but true try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } return ret[0]; }
From source file:com.zhonghui.tool.controller.HttpClient.java
/** * Post/*from w w w . ja v a 2 s. co m*/ * * @return * @throws ProtocolException */ private HttpURLConnection createConnection(String encoding) throws ProtocolException { HttpURLConnection httpURLConnection = null; try { httpURLConnection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { e.printStackTrace(); return null; } httpURLConnection.setConnectTimeout(this.connectionTimeout);// httpURLConnection.setReadTimeout(this.readTimeOut);// ? httpURLConnection.setDoInput(true); // ? post? httpURLConnection.setDoOutput(true); // ? post? httpURLConnection.setUseCaches(false);// ? httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=" + encoding); httpURLConnection.setRequestMethod("POST"); return httpURLConnection; }
From source file:org.whispersystems.textsecure.push.PushServiceSocket.java
private void downloadExternalFile(String url, File localDestination) throws IOException { URL downloadUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection(); connection.setRequestProperty("Content-Type", "application/octet-stream"); connection.setRequestMethod("GET"); connection.setDoInput(true); try {// w w w. jav a 2s. co m if (connection.getResponseCode() != 200) { throw new IOException("Bad response: " + connection.getResponseCode()); } OutputStream output = new FileOutputStream(localDestination); InputStream input = connection.getInputStream(); byte[] buffer = new byte[4096]; int read; while ((read = input.read(buffer)) != -1) { output.write(buffer, 0, read); } output.close(); Log.w("PushServiceSocket", "Downloaded: " + url + " to: " + localDestination.getAbsolutePath()); } finally { connection.disconnect(); } }
From source file:com.example.socketmobile.android.warrantychecker.network.UserRegistration.java
private Object fetchWarranty(String id, String authString, String query) throws IOException { InputStream is = null;//w w w.j av a 2 s . com RegistrationApiResponse result = null; RegistrationApiErrorResponse errorResult = null; String authHeader = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP); try { URL url = new URL(baseUrl + id + "/registrations"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(10000 /* milliseconds */); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Authorization", authHeader); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(query); writer.flush(); writer.close(); os.close(); conn.connect(); int response = conn.getResponseCode(); Log.d(TAG, "Warranty query responded: " + response); switch (response / 100) { case 2: is = conn.getInputStream(); RegistrationApiResponse.Reader reader = new RegistrationApiResponse.Reader(); result = reader.readJsonStream(is); break; case 4: case 5: is = conn.getErrorStream(); RegistrationApiErrorResponse.Reader errorReader = new RegistrationApiErrorResponse.Reader(); errorResult = errorReader.readErrorJsonStream(is); break; } } catch (IOException e) { e.printStackTrace(); return null; } finally { if (is != null) { is.close(); } } return (result != null) ? result : errorResult; }
From source file:eu.codeplumbers.cosi.services.CosiSmsService.java
public void sendChangesToCozy() { List<Sms> unSyncedSms = Sms.getAllUnsynced(); int i = 0;//from w w w . jav a 2s .c om for (Sms sms : unSyncedSms) { URL urlO = null; try { JSONObject jsonObject = sms.toJsonObject(); mBuilder.setProgress(unSyncedSms.size(), i, false); mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":"); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new SmsSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_phone))); String remoteId = jsonObject.getString("remoteId"); String requestMethod = ""; if (remoteId.isEmpty()) { urlO = new URL(syncUrl); requestMethod = "POST"; } else { urlO = new URL(syncUrl + remoteId + "/"); requestMethod = "PUT"; } HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod(requestMethod); // set request body jsonObject.remove("remoteId"); long objectId = jsonObject.getLong("id"); jsonObject.remove("id"); OutputStream os = conn.getOutputStream(); os.write(jsonObject.toString().getBytes("UTF-8")); os.flush(); // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONObject jsonObjectResult = new JSONObject(result); if (jsonObjectResult != null && jsonObjectResult.has("_id")) { result = jsonObjectResult.getString("_id"); sms.setRemoteId(result); sms.save(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } i++; } }
From source file:org.runnerup.export.RunKeeperSynchronizer.java
public Status listActivities(List<SyncActivityItem> list) { Status s = connect();//w ww .ja va2s . c o m if (s != Status.OK) { return s; } String requestUrl = REST_URL + fitnessActivitiesUrl; while (requestUrl != null) { try { URL nextUrl = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) nextUrl.openConnection(); conn.setDoInput(true); conn.setRequestMethod(RequestMethod.GET.name()); conn.addRequestProperty("Authorization", "Bearer " + access_token); conn.addRequestProperty("Content-Type", "application/vnd.com.runkeeper.FitnessActivityFeed+json"); InputStream input = new BufferedInputStream(conn.getInputStream()); if (conn.getResponseCode() == HttpStatus.SC_OK) { JSONObject resp = SyncHelper.parse(input); requestUrl = parseForNext(resp, list); s = Status.OK; } else { s = Status.ERROR; } input.close(); conn.disconnect(); } catch (IOException e) { Log.e(Constants.LOG, e.getMessage()); requestUrl = null; s = Status.ERROR; } catch (JSONException e) { Log.e(Constants.LOG, e.getMessage()); requestUrl = null; s = Status.ERROR; } } return s; }
From source file:fr.haploid.webservices.WebServicesTask.java
@Override protected JSONObject doInBackground(Void... params) { try {//ww w .jav a 2s .c o m if (mSendCacheResult) { JSONObject cacheResultMessage = new JSONObject(); cacheResultMessage.put(Cobalt.kJSType, Cobalt.JSTypePlugin); cacheResultMessage.put(Cobalt.kJSPluginName, JSPluginNameWebservices); JSONObject storedData = new JSONObject(); storedData.put(kJSCallId, mCallId); cacheResultMessage.put(Cobalt.kJSData, storedData); int storageSize = WebServicesData.getCountItem(); if (storageSize > 0) { if (mStorageKey != null) { String storedValue = WebServicesPlugin.storedValueForKey(mStorageKey, mFragment); if (storedValue != null) { try { storedData.put(Cobalt.kJSData, WebServicesPlugin .treatData(new JSONObject(storedValue), mProcessData, mFragment)); cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageResult); //cacheResultMessage.put(Cobalt.kJSData, storedData); } catch (JSONException exception) { if (Cobalt.DEBUG) { Log.e(WebServicesPlugin.TAG, TAG + " - doInBackground: value parsing failed for key " + mStorageKey + ". Value: " + storedValue); exception.printStackTrace(); } cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError); storedData.put(kJSText, JSTextUnknownError); } } else { if (Cobalt.DEBUG) Log.w(WebServicesPlugin.TAG, TAG + " - doInBackground: value not found in cache for key " + mStorageKey + "."); cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError); storedData.put(kJSText, JSTextNotFound); } } else { cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError); storedData.put(kJSText, JSTextUnknownError); } } else { if (Cobalt.DEBUG) Log.w(WebServicesPlugin.TAG, TAG + " - doInBackground: cache is empty."); cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError); storedData.put(kJSText, JSTextEmpty); } cacheResultMessage.put(Cobalt.kJSData, storedData); mFragment.sendMessage(cacheResultMessage); } if (mUrl != null && mType != null) { // TODO: later, use Helper /* responseData = WebServicesHelper.downloadFromServer(data.getString(URL), data.getJSONObject(PARAMS), data.getString(TYPE)); if (responseData != null) { responseHolder.put(TEXT, responseData.getResponseData()); responseHolder.put(STATUS_CODE, responseData.getStatusCode()); responseHolder.put(WS_SUCCESS, responseData.isSuccess()); responseHolder.put(CALL_WS, true); } */ Uri.Builder builder = new Uri.Builder(); builder.encodedPath(mUrl); if (!mParams.equals("") && mType.equalsIgnoreCase(JSTypeGET)) builder.encodedQuery(mParams); JSONObject response = new JSONObject(); response.put(kJSSuccess, false); try { URL url = new URL(builder.build().toString()); try { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); if (mTimeout > 0) urlConnection.setConnectTimeout(mTimeout); urlConnection.setRequestMethod(mType); urlConnection.setDoInput(true); if (mHeaders != null) { JSONArray names = mHeaders.names(); if (names != null) { int length = names.length(); for (int i = 0; i < length; i++) { String name = names.getString(i); urlConnection.setRequestProperty(name, mHeaders.get(name).toString()); } } } if (!mParams.equals("") && !mType.equalsIgnoreCase(JSTypeGET)) { urlConnection.setDoOutput(true); OutputStream outputStream = urlConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(outputStream, "UTF-8")); writer.write(mParams); writer.flush(); writer.close(); outputStream.close(); } urlConnection.connect(); int responseCode = urlConnection.getResponseCode(); if (responseCode != -1) { response.put(kJSStatusCode, responseCode); if (responseCode < 400) response.put(kJSSuccess, true); } try { InputStream inputStream; if (responseCode >= 400 && responseCode < 600) inputStream = urlConnection.getErrorStream(); else inputStream = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer buffer = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { buffer.append(line).append("\n"); } if (buffer.length() != 0) response.put(kJSText, buffer.toString()); } catch (IOException exception) { if (Cobalt.DEBUG) { Log.i(WebServicesPlugin.TAG, TAG + " - doInBackground: no DATA returned by server."); exception.printStackTrace(); } } } catch (ProtocolException exception) { if (Cobalt.DEBUG) { Log.e(WebServicesPlugin.TAG, TAG + " - doInBackground: not supported request method type " + mType); exception.printStackTrace(); } } catch (IOException exception) { exception.printStackTrace(); } return response; } catch (MalformedURLException exception) { if (Cobalt.DEBUG) { Log.e(WebServicesPlugin.TAG, TAG + " - doInBackground: malformed url " + builder.build().toString() + "."); exception.printStackTrace(); } } } } catch (JSONException exception) { exception.printStackTrace(); } return null; }
From source file:CloudManagerAPI.java
private HttpURLConnection openConnection(final URL url, final Method method) throws IOException { // open the connection HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // use supplied method and configure the connection connection.setRequestMethod(method.toString()); connection.setDoInput(true); connection.setDoOutput(true);/* w w w . ja va 2 s . c om*/ connection.setUseCaches(false); // set the request headers connection.setRequestProperty(HEADER_KEY_TOKEN, token); connection.setRequestProperty(HEADER_KEY_VERSION, "" + version); return connection; }
From source file:com.licryle.httpposter.HttpPoster.java
/** * Opens a connection to the POST end point specified in the mConf * {@link HttpConfiguration} and sends the content of mEntity. Attempts to * read the answer from the server after the POST Request. * // ww w .j av a2 s . com * @param mConf The {@link HttpConfiguration} of the request. * @param mEntity The Entity to send in the HTTP Post. Should be built using * {@link #_buildEntity}. * * @return The result of the HTTP Post request. Either #SUCCESS, * #FAILURE_CONNECTION, #FAILURE_TRANSFER, #FAILURE_RESPONSE, * #FAILURE_MALFORMEDURL. * * @see HttpConfiguration * @see _ProgressiveEntity */ protected Long _httpPost(HttpConfiguration mConf, _ProgressiveEntity mEntity) { Log.d("HttpPoster", String.format("_httpPost: Entering Instance %d", _iInstanceId)); /******** Open request ********/ try { HttpURLConnection mConn = (HttpURLConnection) mConf.getEndPoint().openConnection(); mConn.setRequestMethod("POST"); mConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + mConf.getHTTPBoundary()); mConn.setDoInput(true); mConn.setDoOutput(true); mConn.setUseCaches(false); mConn.setReadTimeout(mConf.getReadTimeout()); mConn.setConnectTimeout(mConf.getConnectTimeout()); mConn.setInstanceFollowRedirects(false); mConn.connect(); Log.d("HttpPoster", String.format("_httpPost: Connected for Instance %d", _iInstanceId)); try { /********** Write request ********/ _dispatchOnStartTransfer(); Log.d("HttpPoster", String.format("_httpPost: Sending for Instance %d", _iInstanceId)); mEntity.writeTo(mConn.getOutputStream()); mConn.getOutputStream().flush(); mConn.getOutputStream().close(); _iResponseCode = mConn.getResponseCode(); try { Log.d("HttpPoster", String.format("_httpPost: Reading for Instance %d", _iInstanceId)); _readServerAnswer(mConn.getInputStream()); return SUCCESS; } catch (IOException e) { return FAILURE_RESPONSE; } } catch (Exception e) { Log.d("HTTPParser", e.getMessage()); e.printStackTrace(); return FAILURE_TRANSFER; } finally { if (mConn != null) { Log.d("HttpPoster", String.format("_httpPost: Disconnecting Instance %d", _iInstanceId)); mConn.disconnect(); } } } catch (Exception e) { return FAILURE_CONNECTION; } }
From source file:io.confluent.kafka.schemaregistry.client.rest.RestService.java
/** * @param requestUrl HTTP connection will be established with this url. * @param method HTTP method ("GET", "POST", "PUT", etc.) * @param requestBodyData Bytes to be sent in the request body. * @param requestProperties HTTP header properties. * @param responseFormat Expected format of the response to the HTTP request. * @param <T> The type of the deserialized response to the HTTP request. * @return The deserialized response to the HTTP request, or null if no data is expected. *//*ww w . j ava 2 s .c o m*/ private <T> T sendHttpRequest(String requestUrl, String method, byte[] requestBodyData, Map<String, String> requestProperties, TypeReference<T> responseFormat) throws IOException, RestClientException { log.debug(String.format("Sending %s with input %s to %s", method, requestBodyData == null ? "null" : new String(requestBodyData), requestUrl)); HttpURLConnection connection = null; try { URL url = new URL(requestUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); // connection.getResponseCode() implicitly calls getInputStream, so always set to true. // On the other hand, leaving this out breaks nothing. connection.setDoInput(true); for (Map.Entry<String, String> entry : requestProperties.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } connection.setUseCaches(false); if (requestBodyData != null) { connection.setDoOutput(true); OutputStream os = null; try { os = connection.getOutputStream(); os.write(requestBodyData); os.flush(); } catch (IOException e) { log.error("Failed to send HTTP request to endpoint: " + url, e); throw e; } finally { if (os != null) os.close(); } } int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); T result = jsonDeserializer.readValue(is, responseFormat); is.close(); return result; } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) { return null; } else { InputStream es = connection.getErrorStream(); ErrorMessage errorMessage; try { errorMessage = jsonDeserializer.readValue(es, ErrorMessage.class); } catch (JsonProcessingException e) { errorMessage = new ErrorMessage(JSON_PARSE_ERROR_CODE, e.getMessage()); } es.close(); throw new RestClientException(errorMessage.getMessage(), responseCode, errorMessage.getErrorCode()); } } finally { if (connection != null) { connection.disconnect(); } } }