List of usage examples for java.net HttpURLConnection setDoInput
public void setDoInput(boolean doinput)
From source file:com.nbzs.ningbobus.ui.loaders.BusRunInfoReaderLoader.java
private BusLineRunInfoItem downloadOneFeedItem(Integer busLine) { try {/*w w w .j av a2 s .co m*/ URI newUri = URI.create(mFeedUri.toString() + "/" + Integer.toString(busLine) + "/?format=json"); HttpURLConnection conn = (HttpURLConnection) newUri.toURL().openConnection(); InputStream in; int status; conn.setDoInput(true); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("User-Agent", getContext().getString(R.string.user_agent_string)); in = conn.getInputStream(); status = conn.getResponseCode(); if (status < 400) { String result = IOUtils.readStream(in); BusLineRunInfoItem item = new BusLineRunInfoItem(); //result = "{\"RunInfo\" : " + result + "}"; JSONObject jo = new JSONObject(result); //item.setBusLineName(jo.getString("Name")); item.setBusLineCurrentInfo(jo.getString("RunInfo")); //result = URLDecoder.decode(result, "UTF-8"); //item.setBusLineCurrentInfo(result); item.setBusLineName(FeedService.getBusLineFromId(getContext(), busLine)); return item; } conn.disconnect(); } catch (UnknownHostException e) { mActivity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(mActivity, "No network connection.", Toast.LENGTH_SHORT).show(); } }); } catch (IOException e) { Log.d(TAG, "error reading feed"); Log.d(TAG, Log.getStackTraceString(e)); } catch (IllegalStateException e) { Log.d(TAG, "this should not happen"); Log.d(TAG, Log.getStackTraceString(e)); } catch (JSONException e) { Log.d(TAG, "this should not happen"); Log.d(TAG, Log.getStackTraceString(e)); } return null; }
From source file:com.culvereq.vimp.networking.ConnectionHandler.java
public String login(String username, String password) throws IOException { URL requestURL = new URL(loginURL); HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection(); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); String urlParameters = ""; urlParameters += "username=" + username; urlParameters += "&password=" + password; connection.setRequestProperty("Content-Length", "" + urlParameters.getBytes().length); connection.setUseCaches(false);//from w w w . j av a 2s. co m OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(urlParameters); writer.flush(); writer.close(); int responseCode = connection.getResponseCode(); if (responseCode == 200) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString().trim(); } else { return null; } }
From source file:br.bireme.accounts.Authentication.java
public JSONObject getUser(final String user, final String password) throws IOException, ParseException { if (user == null) { throw new NullPointerException("user"); }// w w w . j a v a 2 s . c o m if (password == null) { throw new NullPointerException("password"); } final JSONObject parameters = new JSONObject(); parameters.put("username", user); parameters.put("password", password); parameters.put("service", SERVICE_NAME); parameters.put("format", "json"); //final URL url = new URL("http", host, port, DEFAULT_PATH); final URL url = new URL("http://" + host + DEFAULT_PATH); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoInput(true); connection.setDoOutput(true); connection.connect(); final StringBuilder builder = new StringBuilder(); final BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(connection.getOutputStream(), "UTF-8")); //final String message = parameters.toJSONString(); //System.out.println(message); writer.write(parameters.toJSONString()); writer.newLine(); writer.close(); final int respCode = connection.getResponseCode(); final boolean respCodeOk = (respCode == 200); final BufferedReader reader; if (respCodeOk) { reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); } else { reader = new BufferedReader(new InputStreamReader(connection.getErrorStream())); } while (true) { final String line = reader.readLine(); if (line == null) { break; } builder.append(line); builder.append("\n"); } reader.close(); if (!respCodeOk && (respCode != 401)) { throw new IOException(builder.toString()); } return (JSONObject) new JSONParser().parse(builder.toString()); }
From source file:edu.pdx.cecs.orcycle.UserFeedbackUploader.java
boolean uploadUserInfoV4() { boolean result = false; final String postUrl = mCtx.getResources().getString(R.string.post_url); try {/*from w ww .j av a 2s.co m*/ URL url = new URL(postUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); conn.setRequestProperty("Cycleatl-Protocol-Version", "4"); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); JSONObject jsonUser; if (null != (jsonUser = getUserJSON())) { try { String deviceId = userId; dos.writeBytes(fieldSep + ContentField("user") + jsonUser.toString() + "\r\n"); dos.writeBytes( fieldSep + ContentField("version") + String.valueOf(kSaveProtocolVersion4) + "\r\n"); dos.writeBytes(fieldSep + ContentField("device") + deviceId + "\r\n"); dos.writeBytes(fieldSep); dos.flush(); } catch (Exception ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } finally { dos.close(); } int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); // JSONObject responseData = new JSONObject(serverResponseMessage); Log.v("Jason", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 201 || serverResponseCode == 202) { // TODO: Record somehow that data was uploaded successfully result = true; } } else { result = false; } } catch (IllegalStateException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } catch (JSONException e) { e.printStackTrace(); return false; } return result; }
From source file:com.PAB.ibeaconreference.AppEngineSpatial.java
public static Response getOrPost(Request request) { mErrorMessage = null;//from w w w. j a v a 2 s . co 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) { int a = conn.getResponseCode(); if (a == 401) { response = new Response(a, conn.getHeaderFields(), new byte[] {}); } InputStream a1 = conn.getErrorStream(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); byte[] body = readStream(in); a12 = new String(body, "US-ASCII"); response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body); // List<String> a = conn.getHeaderFields().get("aa"); } } } catch (IOException e) { e.printStackTrace(System.err); } finally { if (conn != null) conn.disconnect(); } return response; }
From source file:dk.clarin.tools.workflow.java
/** * Sends an HTTP GET request to a url//from www . j a v a2 s. c o m * * @param endpoint - The URL of the server. (Example: " http://www.yahoo.com/search") * @param requestString - all the request parameters (Example: "param1=val1¶m2=val2"). Note: This method will add the question mark (?) to the request - DO NOT add it yourself * @return - The response from the end point */ public static int sendRequest(String result, String endpoint, String requestString, bracmat BracMat, String filename, String jobID, boolean postmethod) { int code = 0; String message = ""; //String filelist; if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) { // Send a GET or POST request to the servlet try { // Construct data String requestResult = ""; String urlStr = endpoint; if (postmethod) // HTTP POST { logger.debug("HTTP POST"); StringReader input = new StringReader(requestString); StringWriter output = new StringWriter(); URL endp = new URL(endpoint); HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) endp.openConnection(); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); pipe(input, writer); writer.close(); } catch (IOException e) { throw new Exception("IOException while posting data", e); } finally { if (out != null) out.close(); } } catch (IOException e) { throw new Exception("Connection error (is server running at " + endp + " ?): " + e); } finally { if (urlc != null) { code = urlc.getResponseCode(); if (code == 200) { got200(result, BracMat, filename, jobID, urlc.getInputStream()); } else { InputStream in = urlc.getInputStream(); try { Reader reader = new InputStreamReader(in); pipe(reader, output); reader.close(); requestResult = output.toString(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (in != null) in.close(); } logger.debug("urlc.getResponseCode() == {}", code); message = urlc.getResponseMessage(); didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } urlc.disconnect(); } else { code = 0; didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } //requestResult = output.toString(); logger.debug("postData returns " + requestResult); } else // HTTP GET { logger.debug("HTTP GET"); // Send data if (requestString != null && requestString.length() > 0) { urlStr += "?" + requestString; } URL url = new URL(urlStr); URLConnection conn = url.openConnection(); conn.connect(); // Cast to a HttpURLConnection if (conn instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) conn; code = httpConnection.getResponseCode(); logger.debug("httpConnection.getResponseCode() == {}", code); message = httpConnection.getResponseMessage(); BufferedReader rd; StringBuilder sb = new StringBuilder(); ; //String line; if (code == 200) { got200(result, BracMat, filename, jobID, httpConnection.getInputStream()); } else { // Get the error response rd = new BufferedReader(new InputStreamReader(httpConnection.getErrorStream())); int nextChar; while ((nextChar = rd.read()) != -1) { sb.append((char) nextChar); } rd.close(); requestResult = sb.toString(); didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } else { code = 0; didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } logger.debug("Job " + jobID + " receives status code [" + code + "] from tool."); } catch (Exception e) { //jobs = 0; // No more jobs to process now, probably the tool is not reachable logger.warn("Job " + jobID + " aborted. Reason:" + e.getMessage()); /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")"); } } else { //jobs = 0; // No more jobs to process now, probably the tool is not integrated at all logger.warn("Job " + jobID + " aborted. Endpoint must start with 'http://' or 'https://'. (" + endpoint + ")"); /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")"); } return code; }
From source file:com.culvereq.vimp.networking.ConnectionHandler.java
public ServiceRecord addServiceRecord(TempServiceRecord serviceRecord) throws IOException, JSONException { URL requestURL = new URL(serviceURL + "add"); HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection(); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); String urlParameters = ""; urlParameters += "key=" + Globals.access_key; urlParameters += "&vehicle-id=" + serviceRecord.getParentVehicle().getId(); urlParameters += "&type-id=" + serviceRecord.getType().getValue(); urlParameters += "&service-desc=" + serviceRecord.getDescription(); urlParameters += "&service-date=" + serviceRecord.getServiceDate().getMillis() / 1000L; urlParameters += "&service-mileage=" + serviceRecord.getMileage(); connection.setRequestProperty("Content-Length", "" + urlParameters.getBytes().length); connection.setUseCaches(false);/*from w w w .j a va2 s .co m*/ OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(urlParameters); writer.flush(); writer.close(); int responseCode = connection.getResponseCode(); if (responseCode == 201) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject json = new JSONObject(response.toString()); return new Deserializer().deserializeService(json, response.toString()); } else if (responseCode == 400) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); throw new IOException(response.toString()); } else { throw new IOException("Got response code: " + responseCode); } }
From source file:fr.insalyon.creatis.vip.datamanager.applet.upload.UploadFilesBusiness.java
@Override public void run() { try {/*from w ww . j a va 2s . co m*/ SwingUtilities.invokeAndWait(beforeRunnable); File fileToUpload = null; boolean single = true; if (dataList.size() == 1 && new File(dataList.get(0)).isFile()) { fileToUpload = new File(dataList.get(0)); } else { String fileName = System.getProperty("java.io.tmpdir") + "/file-" + System.nanoTime() + ".zip"; FolderZipper.zipListOfData(dataList, fileName); fileToUpload = new File(fileName); zipFileName = fileToUpload.getName(); single = false; } // Call Servlet URL servletURL = new URL(codebase + "/fr.insalyon.creatis.vip.portal.Main/uploadfilesservice"); HttpURLConnection servletConnection = (HttpURLConnection) servletURL.openConnection(); servletConnection.setDoInput(true); servletConnection.setDoOutput(true); servletConnection.setUseCaches(false); servletConnection.setDefaultUseCaches(false); servletConnection.setChunkedStreamingMode(4096); servletConnection.setRequestProperty("vip-cookie-session", sessionId); servletConnection.setRequestProperty("Content-Type", "application/octet-stream"); servletConnection.setRequestProperty("Content-Length", Long.toString(fileToUpload.length())); servletConnection.setRequestProperty("path", path); servletConnection.setRequestProperty("fileName", fileToUpload.getName()); servletConnection.setRequestProperty("single", single + ""); servletConnection.setRequestProperty("unzip", unzip + ""); servletConnection.setRequestProperty("pool", usePool + ""); long fileSize = fileToUpload.length(); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileToUpload)); OutputStream os = servletConnection.getOutputStream(); try { byte[] buffer = new byte[4096]; long done = 0; while (true) { int bytes = bis.read(buffer); if (bytes < 0) { break; } done += bytes; os.write(buffer, 0, bytes); progressRunnable.setValue((int) (done * 100 / fileSize)); SwingUtilities.invokeAndWait(progressRunnable); } os.flush(); } finally { os.close(); bis.close(); } BufferedReader reader = new BufferedReader(new InputStreamReader(servletConnection.getInputStream())); String operationID = null; try { String line; while ((line = reader.readLine()) != null) { if (line.startsWith("id=")) { operationID = line.split("=")[1]; } System.out.println(line); } } finally { reader.close(); } if (!single) { fileToUpload.delete(); } if (deleteDataList) { for (String data : dataList) { FileUtils.deleteQuietly(new File(data)); } } result = operationID; SwingUtilities.invokeAndWait(afterRunnable); } catch (Exception ex) { result = ex.getMessage(); SwingUtilities.invokeLater(errorRunnable); } }
From source file:com.culvereq.vimp.networking.ConnectionHandler.java
public Vehicle addVehicle(TempVehicle vehicle) throws IOException, JSONException { URL requestURL = new URL(vehicleURL + "add"); HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection(); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); String urlParameters = ""; urlParameters += "key=" + Globals.access_key; urlParameters += "&vehicle-name=" + vehicle.getName(); urlParameters += "&vehicle-type-id=" + vehicle.getType().getValue(); urlParameters += "&vehicle-make=" + vehicle.getMake(); urlParameters += "&vehicle-model" + vehicle.getModel(); urlParameters += "&vehicle-year" + vehicle.getYear(); urlParameters += "&vehicle-mileage" + vehicle.getMileage(); urlParameters += "&vehicle-vin" + vehicle.getVin(); urlParameters += "&vehicle-license-no" + vehicle.getLicenseNumber(); connection.setRequestProperty("Content-Length", "" + urlParameters.getBytes().length); connection.setUseCaches(false);//from w w w .java 2 s . c o m OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(urlParameters); writer.flush(); writer.close(); int responseCode = connection.getResponseCode(); if (responseCode == 201) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); JSONObject json = new JSONObject(response.toString()); return new Deserializer().deserializeVehicle(json, response.toString()); } else if (responseCode == 400) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); throw new IOException(response.toString()); } else { throw new IOException("Got response code: " + responseCode); } }
From source file:com.snaplogic.snaps.lunex.RequestProcessor.java
public String execute(RequestBuilder rBuilder) throws MalformedURLException, IOException { try {//from ww w .jav a 2 s.c o m URL api_url = new URL(rBuilder.getURL()); HttpURLConnection httpUrlConnection = (HttpURLConnection) api_url.openConnection(); httpUrlConnection.setRequestMethod(rBuilder.getMethod().toString()); httpUrlConnection.setDoInput(true); httpUrlConnection.setDoOutput(true); if (rBuilder.getSnapType() != LunexSnaps.Read) { rBuilder.getHeaders().add(Pair.of(CONTENT_LENGTH, rBuilder.getRequestBodyLenght())); } for (Pair<String, String> header : rBuilder.getHeaders()) { if (!StringUtils.isEmpty(header.getKey()) && !StringUtils.isEmpty(header.getValue())) { httpUrlConnection.setRequestProperty(header.getKey(), header.getValue()); } } log.debug(String.format(LUNEX_HTTP_INFO, rBuilder.getSnapType(), rBuilder.getURL(), httpUrlConnection.getRequestProperties().toString())); if (rBuilder.getSnapType() != LunexSnaps.Read) { String paramsJson = null; if (!StringUtils.isEmpty(paramsJson = rBuilder.getRequestBody())) { DataOutputStream cgiInput = new DataOutputStream(httpUrlConnection.getOutputStream()); log.debug(String.format(LUNEX_HTTP_REQ_INFO, paramsJson)); cgiInput.writeBytes(paramsJson); cgiInput.flush(); IOUtils.closeQuietly(cgiInput); } } List<String> input = null; StringBuilder response = new StringBuilder(); try (InputStream iStream = httpUrlConnection.getInputStream()) { input = IOUtils.readLines(iStream); } catch (IOException ioe) { log.warn(String.format(INPUT_STREAM_ERROR, ioe.getMessage())); try (InputStream eStream = httpUrlConnection.getErrorStream()) { if (eStream != null) { input = IOUtils.readLines(eStream); } else { response.append(String.format(INPUT_STREAM_ERROR, ioe.getMessage())); } } catch (IOException ioe1) { log.warn(String.format(INPUT_STREAM_ERROR, ioe1.getMessage())); } } statusCode = httpUrlConnection.getResponseCode(); log.debug(String.format(HTTP_STATUS, statusCode)); if (input != null && !input.isEmpty()) { for (String line : input) { response.append(line); } } return formatResponse(response, rBuilder); } catch (MalformedURLException me) { log.error(me.getMessage(), me); throw me; } catch (IOException ioe) { log.error(ioe.getMessage(), ioe); throw ioe; } catch (Exception ex) { log.error(ex.getMessage(), ex); throw ex; } }