List of usage examples for java.net HttpURLConnection addRequestProperty
public void addRequestProperty(String key, String value)
From source file:org.runnerup.export.RunKeeperUploader.java
JSONObject requestFeed(long from) throws IOException, JSONException { URL newurl = new URL(FEED_URL); HttpURLConnection conn = (HttpURLConnection) newurl.openConnection(); conn.setDoOutput(true);/*from w w w .ja va 2 s.c om*/ conn.setRequestMethod("POST"); conn.addRequestProperty("Authorization", "Bearer " + feed_access_token); FormValues kv = new FormValues(); kv.put("lastPostTime", Long.toString(from)); kv.put("feedItemTypes", FEED_ITEM_TYPES); { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); } int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); InputStream in = new BufferedInputStream(conn.getInputStream()); JSONObject obj = parse(in); conn.disconnect(); if (responseCode == 200) { return obj; } throw new IOException(amsg); }
From source file:com.android.volley.toolbox.http.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError, IOException { HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());// w w w . j a v a 2 s . co m map.putAll(additionalHeaders); String url = request.getUrl(); if (mUrlRewriter != null) { url = mUrlRewriter.rewriteUrl(url); if (url == null) { throw new IOException("URL blocked by rewriter: " + url); } } URL parsedUrl = new URL(url); System.err.println(url); HttpURLConnection connection = openConnection(parsedUrl, request); if (!TextUtils.isEmpty(mUserAgent)) { connection.setRequestProperty(HEADER_USER_AGENT, mUserAgent); } for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:org.onehippo.translate.TranslateWorkflowImpl.java
protected void translate(String sourceLanguage, String targetLanguage, List<String> texts) throws WorkflowException, RepositoryException { try {// w w w . j av a2 s . c om final String parameters = createParamters(texts, targetLanguage, sourceLanguage); if (log.isDebugEnabled()) { log.debug("request to google translate \"{}\" with parameters \"{}\"", GOOGLE_TRANSLATE_URL_V2, parameters); } URL url = new URL(GOOGLE_TRANSLATE_URL_V2); HttpURLConnection connection = null; PrintWriter out = null; Reader in = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty("X-HTTP-Method-Override", "GET"); out = new PrintWriter(connection.getOutputStream()); out.write(parameters); out.flush(); final int status = connection.getResponseCode(); if (status == 200) { String charset = getCharset(connection.getHeaderField("Content-Type")); in = new InputStreamReader(connection.getInputStream(), charset); final String response = IOUtils.toString(in); if (log.isDebugEnabled()) { log.debug("response from google translate reads \"{}\"", response); } JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("translations"); for (int i = 0; i < jsonArray.length(); i++) { String translatedText = jsonArray.getJSONObject(i).getString("translatedText"); if (log.isDebugEnabled()) { log.debug("translated \"{}\" to \"{}\"", texts.get(i), translatedText); } texts.set(i, translatedText); } } else { in = new InputStreamReader(connection.getErrorStream()); log.warn("Failed to translate field, google translate responded with status {}", status); log.warn("Google response: {}", IOUtils.toString(in)); } } finally { if (connection != null) { connection.disconnect(); } IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } catch (JSONException | IOException ex) { session.refresh(false); throw new WorkflowException("Failed to translate document", ex); } }
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 ww .j ava2 s.com*/ 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:export.MapMyRunUploader.java
@Override public Status upload(SQLiteDatabase db, long mID) { Status s;/*from ww w . j a v a 2 s . com*/ if ((s = connect()) != Status.OK) { return s; } TCX tcx = new TCX(db); HttpURLConnection conn = null; Exception ex = null; try { StringWriter writer = new StringWriter(); tcx.export(mID, writer); conn = (HttpURLConnection) new URL(IMPORT_URL).openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); FormValues kv = new FormValues(); kv.put("consumer_key", CONSUMER_KEY); kv.put("u", username); kv.put("p", md5pass); kv.put("o", "json"); kv.put("baretcx", "1"); kv.put("tcx", writer.toString()); { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); InputStream in = new BufferedInputStream(conn.getInputStream()); JSONObject obj = parse(in); conn.disconnect(); JSONObject result = obj.getJSONObject("result").getJSONObject("output").getJSONObject("result"); final String workout_id = result.getString("workout_id"); final String workout_key = result.getString("workout_key"); final JSONObject workout = result.getJSONObject("workout"); final String raw_workout_date = workout.getString("raw_workout_date"); final String workout_type_id = workout.getString("workout_type_id"); kv.clear(); kv.put("consumer_key", CONSUMER_KEY); kv.put("u", username); kv.put("p", md5pass); kv.put("o", "json"); kv.put("workout_id", workout_id); kv.put("workout_key", workout_key); kv.put("workout_type_id", workout_type_id); kv.put("workout_description", "RunnerUp - " + raw_workout_date); kv.put("notes", tcx.getNotes()); kv.put("privacy_setting", "1"); // friends conn = (HttpURLConnection) new URL(UPDATE_URL).openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); in = new BufferedInputStream(conn.getInputStream()); obj = parse(in); conn.disconnect(); return Uploader.Status.OK; } } catch (IOException e) { ex = e; } catch (JSONException e) { ex = e; } s = Uploader.Status.ERROR; s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:com.denimgroup.threadfix.service.defects.utils.RestUtilsImpl.java
@Override public boolean hasXSeraphLoginReason(String urlString, String username, String password) { URL url;/* ww w . jav a 2 s . c o m*/ try { url = new URL(urlString); } catch (MalformedURLException e) { e.printStackTrace(); return false; } try { HttpURLConnection httpConnection; if (proxyService == null) { httpConnection = (HttpURLConnection) url.openConnection(); } else { httpConnection = proxyService.getConnectionWithProxyConfig(url, classToProxy); } setupAuthorization(httpConnection, username, password); httpConnection.addRequestProperty("Content-Type", "application/json"); httpConnection.addRequestProperty("Accept", "application/json"); String headerResult = httpConnection.getHeaderField("X-Seraph-LoginReason"); return headerResult != null && headerResult.equals("AUTHENTICATION_DENIED"); } catch (IOException e) { LOG.warn("IOException encountered while trying to find the response code.", e); } return false; }
From source file:com.daidiansha.acarry.control.network.core.volley.toolbox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError, IOException { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());//from w w w . j a v a 2s .c om map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); if (!TextUtils.isEmpty(mUserAgent)) { connection.setRequestProperty(HEADER_USER_AGENT, mUserAgent); } for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } if (request instanceof MultiPartRequest) { setConnectionParametersForMultipartRequest(connection, (MultiPartRequest) request); } else { setConnectionParametersForRequest(connection, request); } // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could // not be retrieved. // Signal to the caller that something was wrong with the // connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:com.denimgroup.threadfix.service.defects.utils.RestUtilsImpl.java
@Nonnull private InputStream getUrl(String urlString, String username, String password) throws RestException { URL url;//from www .ja v a2 s . c om try { url = new URL(urlString); } catch (MalformedURLException e) { throw new RestUrlException(e, "Unable to make request due to malformed URL. Check the code."); } HttpURLConnection httpConnection = null; try { if (proxyService == null) { httpConnection = (HttpURLConnection) url.openConnection(); } else { httpConnection = proxyService.getConnectionWithProxyConfig(url, classToProxy); } setupAuthorization(httpConnection, username, password); httpConnection.addRequestProperty("Content-Type", "application/json"); httpConnection.addRequestProperty("Accept", "application/json"); InputStream stream = httpConnection.getInputStream(); return stream; } catch (IOException e) { LOG.info("Encountered IOException, unable to continue"); throw new RestIOException(e, "Unable to communicate with the server.", getStatusCode(httpConnection)); } }
From source file:org.runnerup.export.JoggSE.java
@Override public Status upload(final SQLiteDatabase db, final long mID) { Status s;// w ww . j a va 2s. c o m if ((s = connect()) != Status.OK) { return s; } Exception ex = null; HttpURLConnection conn = null; final GPX gpx = new GPX(db); try { final StringWriter gpxString = new StringWriter(); gpx.export(mID, gpxString); conn = (HttpURLConnection) new URL(BASE_URL).openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Host", "jogg.se"); conn.addRequestProperty("Content-Type", "text/xml; charset=utf-8"); final BufferedWriter wr = new BufferedWriter(new PrintWriter(conn.getOutputStream())); saveGPX(wr, gpxString.toString()); wr.flush(); wr.close(); final InputStream in = new BufferedInputStream(conn.getInputStream()); final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); final DocumentBuilder dob = dbf.newDocumentBuilder(); final InputSource is = new InputSource(); is.setByteStream(in); final Document doc = dob.parse(is); conn.disconnect(); conn = null; final String path[] = { "soap:Envelope", "soap:Body", "SaveGpxResponse", "SaveGpxResult", "ResponseStatus", "ResponseCode" }; final Node e = navigate(doc, path); System.err.println("reply: " + e.getTextContent()); if (e != null && e.getTextContent() != null && "OK".contentEquals(e.getTextContent())) { return Uploader.Status.OK; } throw new Exception(e.getTextContent()); } catch (final MalformedURLException e) { ex = e; } catch (final IOException e) { ex = e; } catch (final ParserConfigurationException e) { ex = e; } catch (final SAXException e) { ex = e; } catch (final DOMException e) { ex = e; e.printStackTrace(); } catch (final Exception e) { ex = e; } if (conn != null) conn.disconnect(); s = Uploader.Status.ERROR; s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:com.androidex.volley.toolbox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError, IOException { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());/*w ww . j a v a2 s. c om*/ map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); if (!TextUtils.isEmpty(mUserAgent)) { connection.setRequestProperty(HEADER_USER_AGENT, mUserAgent); } for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } if (request instanceof MultiPartRequest) { setConnectionParametersForMultipartRequest(connection, request); } else { setConnectionParametersForRequest(connection, request); } // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could // not be retrieved. // Signal to the caller that something was wrong with the // connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }