List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java
/** * Upload ontology content on specified dataset. Graph used is the default * one except if specified/*from ww w . j a v a2 s .c o m*/ * * @param ontology * @param datasetName * @param graphName * @throws IOException * @throws HttpException */ public static void uploadOntology(InputStream ontology, String datasetName, @Nullable String graphName) throws IOException, HttpException { graphName = Strings.emptyToNull(graphName); logger.info("upload ontology in dataset: " + datasetName + " graph:" + Strings.nullToEmpty(graphName)); boolean createGraph = (graphName != null) ? true : false; String dataSetEncoded = URLEncoder.encode(datasetName, "UTF-8"); String graphEncoded = createGraph ? URLEncoder.encode(graphName, "UTF-8") : null; URL url = new URL(HOST + '/' + dataSetEncoded + "/data" + (createGraph ? "?graph=" + graphEncoded : "")); final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); String boundary = "------------------" + System.currentTimeMillis() + Long.toString(Math.round(Math.random() * 1000)); httpConnection.setUseCaches(false); httpConnection.setRequestMethod("POST"); httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); httpConnection.setRequestProperty("Connection", "keep-alive"); httpConnection.setRequestProperty("Cache-Control", "no-cache"); // set content httpConnection.setDoOutput(true); final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream()); out.write(BOUNDARY_DECORATOR + boundary + EOL); out.write("Content-Disposition: form-data; name=\"files[]\"; filename=\"ontology.owl\"" + EOL); out.write("Content-Type: application/octet-stream" + EOL + EOL); out.write(CharStreams.toString(new InputStreamReader(ontology))); out.write(EOL + BOUNDARY_DECORATOR + boundary + BOUNDARY_DECORATOR + EOL); out.close(); // handle HTTP/HTTPS strange behaviour httpConnection.connect(); httpConnection.disconnect(); // handle response switch (httpConnection.getResponseCode()) { case HttpURLConnection.HTTP_CREATED: checkState(createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage()); break; case HttpURLConnection.HTTP_OK: checkState(!createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage()); break; default: throw new HttpException( httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage()); } }
From source file:com.paymaya.sdk.android.common.network.AndroidClient.java
@Override public Response call(Request request) { HttpURLConnection conn = initializeConnection(request); try {/* w w w . jav a 2s . com*/ switch (request.getMethod()) { case GET: conn.setRequestMethod("GET"); break; case POST: conn.setRequestMethod("POST"); break; default: throw new RuntimeException("Invalid method " + request.getMethod()); } if (request.getBody() != null) { conn.setDoOutput(true); write(conn.getOutputStream(), request.getBody()); } int code = conn.getResponseCode(); String message = conn.getResponseMessage(); String response; if (code < 200 || code > 299) { response = read(conn.getErrorStream()); } else { response = read(conn.getInputStream()); } Log.d(TAG, "Status: " + code + " " + message); Log.d(TAG, "Response: " + new JSONObject(response).toString(2)); return new Response(code, response); } catch (IOException | JSONException e) { Log.e(TAG, e.getMessage()); return new Response(-1, ""); } finally { conn.disconnect(); } }
From source file:export.GarminUploader.java
private Status connectOld() throws MalformedURLException, IOException, JSONException { Status s = Status.NEED_AUTH;//from w w w .j a v a 2s . c o m s.authMethod = Uploader.AuthMethod.USER_PASS; HttpURLConnection conn = null; /** * connect to START_URL to get cookies */ conn = (HttpURLConnection) new URL(START_URL).openConnection(); { int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); getCookies(conn); if (responseCode != 200) { System.err.println("GarminUploader::connect() - got " + responseCode + ", msg: " + amsg); } } conn.disconnect(); /** * Then login using a post */ String login = LOGIN_URL; FormValues kv = new FormValues(); kv.put("login", "login"); kv.put("login:loginUsernameField", username); kv.put("login:password", password); kv.put("login:signInButton", "Sign In"); kv.put("javax.faces.ViewState", "j_id1"); conn = (HttpURLConnection) new URL(login).openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); addCookies(conn); { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); System.err.println("code: " + responseCode + ", msg=" + amsg); getCookies(conn); } conn.disconnect(); /** * An finally check that all is OK */ return checkLogin(); }
From source file:export.GarminUploader.java
@Override public Status connect() { Status s = Status.NEED_AUTH;//w w w .j a va 2 s . c om s.authMethod = Uploader.AuthMethod.USER_PASS; if (username == null || password == null) { return s; } if (isConnected) { return Status.OK; } Exception ex = null; HttpURLConnection conn = null; logout(); try { conn = (HttpURLConnection) new URL(CHOOSE_URL).openConnection(); conn.setInstanceFollowRedirects(false); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); getCookies(conn); System.err.println("GarminUploader.connect() CHOOSE_URL => code: " + responseCode + ", msg: " + amsg); if (responseCode == 200) { return connectOld(); } else if (responseCode == 302) { return connectNew(); } } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } catch (JSONException 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:org.callimachusproject.test.WebResource.java
public void update(String sparql) throws Exception { HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/sparql-update"); con.setDoOutput(true);/* w w w .j a v a2 s .c om*/ OutputStream out = con.getOutputStream(); try { out.write(sparql.getBytes("UTF-8")); } finally { out.close(); } Assert.assertEquals(con.getResponseMessage(), 204, con.getResponseCode()); }
From source file:it.baywaylabs.jumpersumo.robot.ServerPolling.java
/** * This method is called when invoke <b>execute()</b>.<br /> * Do not invoke manually. Use: new ServerPolling().execute(url1, url2, url3); * * @param sUrl List of Url that will be download. * @return null if all is going ok.//from w w w.j av a 2 s . c om */ @Override protected String doInBackground(String... sUrl) { InputStream input = null; OutputStream output = null; File folder = new File(Constants.DIR_ROBOT); String baseName = FilenameUtils.getBaseName(sUrl[0]); String extension = FilenameUtils.getExtension(sUrl[0]); Log.d(TAG, "FileName: " + baseName + " - FileExt: " + extension); if (!folder.exists()) { folder.mkdir(); } HttpURLConnection connection = null; if (!f.isUrl(sUrl[0])) return "Url malformed!"; try { URL url = new URL(sUrl[0]); connection = (HttpURLConnection) url.openConnection(); connection.connect(); // expect HTTP 200 OK, so we don't mistakenly save error report // instead of the file if (!sUrl[0].endsWith(".csv") && connection.getResponseCode() != HttpURLConnection.HTTP_OK) { return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage(); } // this will be useful to display download percentage // might be -1: server did not report the length int fileLength = connection.getContentLength(); // download the file input = connection.getInputStream(); output = new FileOutputStream(folder.getAbsolutePath() + "/" + baseName + "." + extension); byte data[] = new byte[4096]; long total = 0; int count; while ((count = input.read(data)) != -1) { // allow canceling with back button if (isCancelled()) { input.close(); return null; } total += count; // publishing the progress.... if (fileLength > 0) // only if total length is known publishProgress((int) (total * 100 / fileLength)); output.write(data, 0, count); } } catch (Exception e) { Log.e(TAG, e.getMessage()); return e.toString(); } finally { try { if (output != null) output.close(); if (input != null) input.close(); } catch (IOException ignored) { } if (connection != null) connection.disconnect(); } return null; }
From source file:org.callimachusproject.test.WebResource.java
public void put(String type, byte[] body) throws IOException { HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection(); con.setRequestMethod("PUT"); con.setRequestProperty("If-Match", "*"); con.setRequestProperty("Content-Type", type); con.setDoOutput(true);/*from ww w.ja v a 2 s .c o m*/ OutputStream out = con.getOutputStream(); try { out.write(body); } finally { out.close(); } Assert.assertEquals(con.getResponseMessage(), 204, con.getResponseCode()); }
From source file:carolina.pegaLatLong.LatLong.java
private void buscaLtLong(List<InformacoesTxt> lista) throws MalformedURLException, IOException, ParseException { String status = "Processando..."; edtEncontrados.setText("Encontrados:"); edtNaoEncontrados.setText("No encontrados:"); edtMaisDeUm.setText("Mais de um encontrados:"); edtProcessados.setText("Processados:"); edtStatus.setText(status);// w w w .jav a 2 s . com int processados = 1; URL ul; for (InformacoesTxt in : lista) { if (processados == 2499) { break; } edtProcessados.setText("Processados: " + processados); String resto = ""; String vet[] = in.getEndereco().split(" "); for (String vet1 : vet) { resto += vet1 + "+"; } // String vet2[] = in.getBairro().split(" "); // for (String vet21 : vet2) { // resto += vet21 + "+"; // } // // String vet3[] = in.getCep().split(" "); // for (String vet31 : vet3) { // resto += vet31 + "+"; // } String vet4[] = in.getCidade().split(" "); for (String vet41 : vet4) { resto += vet41 + "+"; } ul = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=" + resto + "&key=AIzaSyDFg9GJIbgHKbZP3b5H2qRV_cAhhvlBaoE"); //System.err.println("URL: " + ul); HttpURLConnection conn = (HttpURLConnection) ul.openConnection(); // conn.setRequestMethod("GET"); //conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { listaBadRequest.add(in); System.err.println("Codigo: " + conn.getResponseMessage()); //System.err.println("URL: " + ul); //JOptionPane.showMessageDialog(null, "Falha ao obter a localizao!"); //break; } else { BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream())); String pega = ""; String result = ""; while ((pega = bf.readLine()) != null) { result += pega; } System.err.println(result); org.json.simple.parser.JSONParser parser = new org.json.simple.parser.JSONParser(); Object obj = parser.parse(result); JSONObject tudo = (JSONObject) obj; JSONArray arrayResultado = (JSONArray) tudo.get("results"); if (arrayResultado.isEmpty()) { listaNaoEncontrados.add(in); edtNaoEncontrados.setText("No encontrados: " + listaNaoEncontrados.size()); } else if (arrayResultado.size() == 1) { JSONObject primeiro = (JSONObject) arrayResultado.get(0); JSONObject jsonObject3 = (JSONObject) primeiro.get("geometry"); JSONObject location = (JSONObject) jsonObject3.get("location"); InformacaoGerada gerado = new InformacaoGerada(); gerado.setEnderecoFormatado(primeiro.get("formatted_address").toString()); String latitude = location.get("lat").toString().replace(".", ","); gerado.setLatitude(latitude); String longitude = location.get("lng").toString().replace(".", ","); gerado.setLongitude(longitude); listaResultado.add(gerado); edtEncontrados.setText("Encontrados: " + listaResultado.size()); } else { listaMaisDeUm.add(in); edtMaisDeUm.setText("Mais de um encontrados: " + listaMaisDeUm.size()); } // System.err.println("Endereo Formatado: " + primeiro.get("formatted_address")); // System.out.println("Lat = " + location.get("lat")); // System.out.println("Lng = " + location.get("lng")); } processados++; } edtStatus.setForeground(Color.GREEN); edtStatus.setText("Concludo"); btnGerar.setEnabled(true); }
From source file:sdmx.net.service.wb.WBRESTServiceRegistry.java
private StructureType retrieve(String urlString) throws MalformedURLException, IOException, ParseException { Logger.getLogger("sdmx").info("ILORestServiceRegistry: retrieve " + urlString); URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); conn.addRequestProperty("Accept-Encoding", "identity"); if (conn.getResponseCode() != 200) { throw new IOException(conn.getResponseMessage()); }//www .ja va 2 s .c o m InputStream in = conn.getInputStream(); if (SdmxIO.isSaveXml()) { String name = System.currentTimeMillis() + ".xml"; FileOutputStream file = new FileOutputStream(name); IOUtils.copy(in, file); in = new FileInputStream(name); } //FileOutputStream temp = new FileOutputStream("temp.xml"); //org.apache.commons.io.IOUtils.copy(in, temp); //temp.close(); //in.close(); //in = new FileInputStream("temp.xml"); ParseParams params = new ParseParams(); params.setRegistry(this); StructureType st = SdmxIO.parseStructure(params, in); if (st == null) { System.out.println("St is null!"); } else { if (SdmxIO.isSaveXml()) { String name = System.currentTimeMillis() + "-21.xml"; FileOutputStream file = new FileOutputStream(name); Sdmx21StructureWriter.write(st, file); } } return st; }
From source file:org.whispersystems.textsecure.push.PushServiceSocket.java
private HttpURLConnection makeBaseRequest(String urlFragment, String method, String body) throws NonSuccessfulResponseCodeException, PushNetworkException { HttpURLConnection connection = getConnection(urlFragment, method, body); int responseCode; String responseMessage;/* w w w.ja va 2 s . c o m*/ String response; try { responseCode = connection.getResponseCode(); responseMessage = connection.getResponseMessage(); } catch (IOException ioe) { throw new PushNetworkException(ioe); } switch (responseCode) { case 413: connection.disconnect(); throw new RateLimitException("Rate limit exceeded: " + responseCode); case 401: case 403: connection.disconnect(); throw new AuthorizationFailedException("Authorization failed!"); case 404: connection.disconnect(); throw new NotFoundException("Not found"); case 409: try { response = Util.readFully(connection.getErrorStream()); } catch (IOException e) { throw new PushNetworkException(e); } throw new MismatchedDevicesException(new Gson().fromJson(response, MismatchedDevices.class)); case 410: try { response = Util.readFully(connection.getErrorStream()); } catch (IOException e) { throw new PushNetworkException(e); } throw new StaleDevicesException(new Gson().fromJson(response, StaleDevices.class)); case 417: throw new ExpectationFailedException(); } if (responseCode != 200 && responseCode != 204) { throw new NonSuccessfulResponseCodeException("Bad response: " + responseCode + " " + responseMessage); } return connection; }