List of usage examples for java.net HttpURLConnection addRequestProperty
public void addRequestProperty(String key, String value)
From source file:export.NikePlus.java
JSONObject makeGetRequest(String url) throws MalformedURLException, IOException, JSONException { HttpURLConnection conn = null; try {/*from www . jav a2s. com*/ conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); conn.addRequestProperty("Accept", "application/json"); conn.addRequestProperty("User-Agent", USER_AGENT); conn.addRequestProperty("appid", APP_ID); final InputStream in = new BufferedInputStream(conn.getInputStream()); final JSONObject reply = parse(in); final int code = conn.getResponseCode(); conn.disconnect(); if (code == 200) return reply; } finally { if (conn != null) conn.disconnect(); } return new JSONObject(); }
From source file:export.FormCrawler.java
protected void addCookies(HttpURLConnection conn) { boolean first = true; StringBuffer buf = new StringBuffer(); for (String cookie : cookies) { if (!first) buf.append("; "); buf.append(cookie.split(";", 2)[0]); first = false;/*from w ww . j av a 2 s . c o m*/ } conn.addRequestProperty("Cookie", buf.toString()); }
From source file:com.sandklef.coachapp.http.HttpAccess.java
public void downloadVideo(String clubUri, String file, String videoUuid) throws HttpAccessException { try {//www . j a v a 2 s .c o m //$ GET http://localhost:3000/v0.0.0/clubs/<ID>/videos/uuid/<ID>/download // String file = LocalStorage.getInstance().getDownloadMediaDir() + "/" + videoUuid + SERVER_VIDEO_SUFFIX; int TIMEOUT_CONNECTION = 5000;//5sec int TIMEOUT_SOCKET = 30000;//30sec String urlServer = urlBase + HttpSettings.API_VERSION + HttpSettings.PATH_SEPARATOR + HttpSettings.VIDEO_URL_PATH + HttpSettings.UUID_PATH + videoUuid + HttpSettings.PATH_SEPARATOR + HttpSettings.DOWNLOAD_PATH; /* String urlServer = urlBase + HttpSettings.API_VERSION + HttpSettings.CLUB_PATH + HttpSettings.PATH_SEPARATOR + clubUri + HttpSettings.PATH_SEPARATOR + HttpSettings.VIDEO_URL_PATH + HttpSettings.UUID_PATH + videoUuid + HttpSettings.PATH_SEPARATOR + HttpSettings.DOWNLOAD_PATH ; */ URL url = new URL(urlServer); long startTime = System.currentTimeMillis(); Log.i(LOG_TAG, "video download beginning: " + urlServer); //Open a connection to that URL. HttpURLConnection ucon = (HttpURLConnection) url.openConnection(); ucon.setRequestProperty("X-Token", LocalStorage.getInstance().getLatestUserToken()); ucon.addRequestProperty("X-Instance", LocalStorage.getInstance().getCurrentClub()); ucon.setRequestMethod(HttpSettings.HTTP_GET); //this timeout affects how long it takes for the app to realize there's a connection problem ucon.setReadTimeout(TIMEOUT_CONNECTION); ucon.setConnectTimeout(TIMEOUT_SOCKET); Log.d(LOG_TAG, " and now to ...1"); //Define InputStreams to read from the HttpURLConnection // uses 3KB download buffer InputStream is = ucon.getInputStream(); Log.d(LOG_TAG, " and now to ...1"); BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5); Log.d(LOG_TAG, " and now to ...2 to file: " + file); FileOutputStream outStream = new FileOutputStream(file); Log.d(LOG_TAG, " and now to ..31"); byte[] buff = new byte[5 * 1024]; System.err.println("For those about to ... file: " + file); //Read bytes (and store them) until there is nothing more to read(-1) int len; while ((len = inStream.read(buff)) != -1) { outStream.write(buff, 0, len); } Log.d(LOG_TAG, "response code: " + ucon.getResponseCode()); //clean up outStream.flush(); outStream.close(); inStream.close(); Log.d(LOG_TAG, "For those about to ..."); Log.d(LOG_TAG, "download completed in " + ((System.currentTimeMillis() - startTime) / 1000) + " sec"); if (!HttpSettings.isResponseOk(ucon.getResponseCode())) { throw new HttpAccessException( "Failed downloading video, response from server " + ucon.getResponseCode(), HttpAccessException.ACCESS_ERROR); } } catch (FileNotFoundException e) { e.printStackTrace(); throw new HttpAccessException("Failed downloading video", e, HttpAccessException.FILE_NOT_FOUND); } catch (Exception e) { e.printStackTrace(); throw new HttpAccessException("Failed downloading video", e, HttpAccessException.NETWORK_ERROR); } }
From source file:org.runnerup.export.RunningAHEAD.java
@Override public Uploader.Status upload(SQLiteDatabase db, final long mID) { Status s;/*from w w w.j a v a 2s . c om*/ if ((s = connect()) != Status.OK) { return s; } String URL = IMPORT_URL + "?access_token=" + access_token; TCX tcx = new TCX(db); HttpURLConnection conn = null; Exception ex = null; try { StringWriter writer = new StringWriter(); tcx.export(mID, writer); conn = (HttpURLConnection) new URL(URL).openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Encoding", "gzip"); OutputStream out = new GZIPOutputStream(new BufferedOutputStream(conn.getOutputStream())); out.write(writer.toString().getBytes()); out.flush(); out.close(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); System.err.println("code: " + responseCode + ", amsg: " + amsg); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); JSONObject obj = parse(in); JSONObject data = obj.getJSONObject("data"); boolean found = false; if (found == false) { try { found = data.getJSONArray("workoutIds").length() == 1; } catch (JSONException e) { } } if (found == false) { try { found = data.getJSONArray("ids").length() == 1; } catch (JSONException e) { } } if (!found) { System.err.println("Unhandled response from RunningAHEAD: " + obj); } if (responseCode == 200 && found) { conn.disconnect(); return Status.OK; } ex = new Exception(amsg); } 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.tc.rest.client.JsonClient.java
@Override public String compressAndPost(String json, String strurl) { StringBuilder builder = new StringBuilder(); HttpURLConnection conn = null; try {/*from w w w .j a v a2s. c om*/ URL url = new URL(strurl); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.addRequestProperty("Content-Encoding", "gzip"); if (this.useCreds) { this.applyCredentials(conn); } byte[] byteMe = CompressionUtils.compress(json.getBytes()); conn.setRequestProperty("Content-Length", String.valueOf(byteMe.length)); OutputStream os = conn.getOutputStream(); os.write(byteMe); os.flush(); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; logger.log(Level.INFO, "Output from Server .... \n"); while ((output = br.readLine()) != null) { builder.append(output); } } catch (IOException e) { logger.log(Level.SEVERE, null, e); } finally { conn.disconnect(); } return builder.toString(); }
From source file:in.rab.ordboken.NeClient.java
private JSONObject publicApiRequest(String requestUrl) throws IOException, JSONException, ParserException { URL url = new URL(requestUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.addRequestProperty("Accept", "application/json"); urlConnection.connect();//from w w w . jav a2s . com try { if (urlConnection.getResponseCode() != 200) { throw new ParserException("Unexpected response: " + urlConnection.getResponseCode()); } return new JSONObject(inputStreamToString(urlConnection.getInputStream())); } finally { urlConnection.disconnect(); } }
From source file:org.runnerup.export.NikePlusSynchronizer.java
JSONObject makeGetRequest(String url) throws MalformedURLException, IOException, JSONException { HttpURLConnection conn = null; try {// ww w. j a v a 2 s . c o m conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod(RequestMethod.GET.name()); conn.addRequestProperty("Accept", "application/json"); conn.addRequestProperty("User-Agent", USER_AGENT); conn.addRequestProperty("appid", APP_ID); final InputStream in = new BufferedInputStream(conn.getInputStream()); final JSONObject reply = SyncHelper.parse(in); final int code = conn.getResponseCode(); conn.disconnect(); if (code == HttpStatus.SC_OK) return reply; } finally { if (conn != null) conn.disconnect(); } return new JSONObject(); }
From source file:org.runnerup.export.FormCrawler.java
protected void addCookies(HttpURLConnection conn) { boolean first = true; StringBuilder buf = new StringBuilder(); for (String cookie : cookies) { if (!first) buf.append("; "); buf.append(cookie.split(";", 2)[0]); first = false;//from www . jav a 2s .c o m } conn.addRequestProperty("Cookie", buf.toString()); }
From source file:org.runnerup.export.RunningAHEADSynchronizer.java
@Override public Status upload(SQLiteDatabase db, final long mID) { Status s;/*from www . j ava 2s .c o m*/ if ((s = connect()) != Status.OK) { return s; } String URL = IMPORT_URL + "?access_token=" + access_token; TCX tcx = new TCX(db); HttpURLConnection conn = null; Exception ex = null; try { StringWriter writer = new StringWriter(); tcx.export(mID, writer); conn = (HttpURLConnection) new URL(URL).openConnection(); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Content-Encoding", "gzip"); OutputStream out = new GZIPOutputStream(new BufferedOutputStream(conn.getOutputStream())); out.write(writer.toString().getBytes()); out.flush(); out.close(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); Log.e(getName(), "code: " + responseCode + ", amsg: " + amsg); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); JSONObject obj = SyncHelper.parse(in); JSONObject data = obj.getJSONObject("data"); boolean found = false; if (found == false) { try { found = data.getJSONArray("workoutIds").length() == 1; } catch (JSONException e) { } } if (found == false) { try { found = data.getJSONArray("ids").length() == 1; } catch (JSONException e) { } } if (!found) { Log.e(getName(), "Unhandled response from RunningAHEADSynchronizer: " + obj); } if (responseCode == HttpStatus.SC_OK && found) { conn.disconnect(); return Status.OK; } ex = new Exception(amsg); } catch (IOException e) { ex = e; } catch (JSONException e) { ex = e; } s = Synchronizer.Status.ERROR; s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:ai.grakn.engine.loader.client.LoaderClient.java
/** * Send an insert query to one host/*from ww w .j a v a2 s .co m*/ */ private String executePost(HttpURLConnection connection, String body) { try { // create post connection.setRequestMethod(REST.HttpConn.POST_METHOD); connection.addRequestProperty(REST.HttpConn.CONTENT_TYPE, REST.HttpConn.APPLICATION_POST_TYPE); // add body and execute connection.setRequestProperty(REST.HttpConn.CONTENT_LENGTH, Integer.toString(body.length())); connection.getOutputStream().write(body.getBytes(REST.HttpConn.UTF8)); connection.getOutputStream().flush(); // get response return IOUtils.toString(connection.getInputStream()); } catch (HTTPException e) { LOG.error(ErrorMessage.ERROR_IN_DISTRIBUTED_TRANSACTION.getMessage(connection.getURL().toString(), e.getStatusCode(), getResponseMessage(connection))); } catch (IOException e) { LOG.error(ErrorMessage.ERROR_COMMUNICATING_TO_HOST.getMessage(connection.getURL().toString())); } finally { connection.disconnect(); } return null; }