List of usage examples for java.net HttpURLConnection getErrorStream
public InputStream getErrorStream()
From source file:com.sonian.elasticsearch.http.jetty.HttpClient.java
public HttpClientResponse request(String method, String path, byte[] data) { ObjectMapper mapper = new ObjectMapper(); URL url;//w w w .j a v a 2 s . c o m try { url = new URL(baseUrl, path); } catch (MalformedURLException e) { throw new ElasticsearchException("Cannot parse " + path, e); } HttpURLConnection urlConnection; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(method); if (data != null) { urlConnection.setDoOutput(true); } if (encodedAuthorization != null) { urlConnection.setRequestProperty("Authorization", "Basic " + encodedAuthorization); } urlConnection.connect(); } catch (IOException e) { throw new ElasticsearchException("", e); } if (data != null) { OutputStream outputStream = null; try { outputStream = urlConnection.getOutputStream(); outputStream.write(data); } catch (IOException e) { throw new ElasticsearchException("", e); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { throw new ElasticsearchException("", e); } } } } int errorCode = -1; try { errorCode = urlConnection.getResponseCode(); InputStream inputStream = urlConnection.getInputStream(); return new HttpClientResponse(mapper.readValue(inputStream, Map.class), errorCode, null); } catch (IOException e) { InputStream errStream = urlConnection.getErrorStream(); String body = null; try { body = Streams.copyToString(new InputStreamReader(errStream)); } catch (IOException e1) { throw new ElasticsearchException("problem reading error stream", e1); } Map m = newHashMap(); m.put("body", body); return new HttpClientResponse(m, errorCode, e); } finally { urlConnection.disconnect(); } }
From source file:com.offbynull.portmapper.upnpigd.UpnpIgdController.java
private Map<String, String> performRequest(String action, ImmutablePair<String, String>... params) { byte[] outgoingData = createRequestXml(action, params); HttpURLConnection conn = null; try {/* www . j av a 2 s . c o m*/ URL url = controlUrl.toURL(); conn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); conn.setRequestMethod("POST"); conn.setReadTimeout(3000); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "text/xml"); conn.setRequestProperty("SOAPAction", serviceType + "#" + action); conn.setRequestProperty("Connection", "Close"); } catch (IOException ex) { throw new IllegalStateException(ex); // should never happen } try (OutputStream os = conn.getOutputStream()) { os.write(outgoingData); } catch (IOException ex) { IOUtils.close(conn); throw new ResponseException(ex); } byte[] incomingData; int respCode; try { respCode = conn.getResponseCode(); } catch (IOException ioe) { IOUtils.close(conn); throw new ResponseException(ioe); } if (respCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { try (InputStream is = conn.getErrorStream()) { incomingData = IOUtils.toByteArray(is); } catch (IOException ex) { IOUtils.close(conn); throw new ResponseException(ex); } } else { try (InputStream is = conn.getInputStream()) { incomingData = IOUtils.toByteArray(is); } catch (IOException ex) { IOUtils.close(conn); throw new ResponseException(ex); } } return parseResponseXml(action + "Response", incomingData); }
From source file:com.twilio.sdk.TwilioRestClient.java
@Override public TwilioRestResponse request(String path, String method, Map<String, String> vars) throws TwilioRestException { String encoded = ""; if (vars != null && !vars.isEmpty()) { for (String key : vars.keySet()) { try { encoded += "&" + key + "=" + URLEncoder.encode(vars.get(key), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new TwilioRestException(e); }//w w w .j a v a 2 s . com } encoded = encoded.substring(1); } // construct full url String url = this.endpoint + path; // if GET and vars, append them if (method.toUpperCase().equals("GET")) url += ((path.indexOf('?') == -1) ? "?" : "&") + encoded; try { HttpURLConnection con = openConnection(url); String userpass = this.accountSid + ":" + this.authToken; String encodeuserpass = new String(Base64.encodeBase64(userpass.getBytes())); con.setRequestProperty("Authorization", "Basic " + encodeuserpass); con.setDoOutput(true); // initialize a new curl object if (method.toUpperCase().equals("GET")) { con.setRequestMethod("GET"); } else if (method.toUpperCase().equals("POST")) { con.setRequestMethod("POST"); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); out.write(encoded); out.close(); } else if (method.toUpperCase().equals("PUT")) { con.setRequestMethod("PUT"); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); out.write(encoded); out.close(); } else if (method.toUpperCase().equals("DELETE")) { con.setRequestMethod("DELETE"); } else { throw new TwilioRestException("Unknown method " + method); } BufferedReader in = null; try { if (con.getInputStream() != null) { in = new BufferedReader(new InputStreamReader(con.getInputStream())); } } catch (IOException e) { if (con.getErrorStream() != null) { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); } } if (in == null) { throw new TwilioRestException("Unable to read response from server"); } StringBuilder decodedString = new StringBuilder(); String line; while ((line = in.readLine()) != null) { decodedString.append(line); } in.close(); // get result code int responseCode = con.getResponseCode(); return new TwilioRestResponse(url, decodedString.toString(), responseCode); } catch (MalformedURLException e) { throw new TwilioRestException(e); } catch (IOException e) { throw new TwilioRestException(e); } }
From source file:TaxSvc.TaxSvc.java
public GetTaxResult GetTax(GetTaxRequest req) { //Create URL//from w ww. j av a2 s . c om String taxget = svcURL + "/1.0/tax/get"; URL url; HttpURLConnection conn; try { //Connect to URL with authorization header, request content. url = new URL(taxget); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content conn.setRequestProperty("Authorization", encoded); //Add authorization header conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); //Tells the serializer to only include those parameters that are not null String content = mapper.writeValueAsString(req); //System.out.println(content); //Uncomment to see the content of the request object conn.setRequestProperty("Content-Length", Integer.toString(content.length())); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(content); wr.flush(); wr.close(); conn.disconnect(); if (conn.getResponseCode() != 200) //If we didn't get a success back, print out the error. { GetTaxResult res = mapper.readValue(conn.getErrorStream(), GetTaxResult.class); //Deserializes the response return res; } else //Otherwise, print out the total tax calculated { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); GetTaxResult res = mapper.readValue(conn.getInputStream(), GetTaxResult.class); //Deserializes the response return res; } } catch (IOException e) { e.printStackTrace(); return null; } }
From source file:com.mycompany.grupo6ti.GenericResource.java
@PUT @Produces("application/json") @Path("/nuevaOc/{canal}/{cant}/{sku}/{proveedor}/{cliente}/{precio}/{fechae}") public String hacerOrdenCompra(@PathParam("canal") String canal, @PathParam("cant") String cant, @PathParam("sku") String sku, @PathParam("proveedor") String proveedor, @PathParam("cliente") String cliente, @PathParam("precio") String precio, @PathParam("fechae") String fechae) throws MalformedURLException, IOException { try {/*from w w w . j a v a2 s . c om*/ URL url = new URL("http://localhost:83/crear"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream is; conn.setRequestProperty("Accept-Charset", "UTF-8"); conn.setRequestProperty("Content-Type", "application/json"); conn.setUseCaches(true); conn.setRequestMethod("PUT"); conn.setDoOutput(true); conn.setDoInput(true); String sss = "{\n" + " \"cliente\": \"" + cliente + "\",\n" + " \"proveedor\": \"" + proveedor + "\",\n" + " \"sku\": \"" + sku + "\",\n" + " \"fechaEntrega\": \"" + fechae + "\",\n" + " \"precioUnitario\": \"" + precio + "\",\n" + " \"cantidad\": \"" + cant + "\",\n" + " \"canal\": \"" + canal + "\"\n" + "}"; OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write(sss); out.flush(); out.close(); if (conn.getResponseCode() >= 400) { is = conn.getErrorStream(); } else { is = conn.getInputStream(); } String result2 = ""; BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; while ((line = rd.readLine()) != null) { result2 += line; } rd.close(); return result2; } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return ("[\"Test\", \"Funcionando Bien\"]"); }
From source file:com.app.milesoft.facebook.Util.java
/** * Connect to an HTTP URL and return the response as a string. * * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url - the resource to open: must be a welformed URL * @param method - the HTTP method to use ("GET", "POST", etc.) * @param params - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String/*ww w. j a va2 s . c o m*/ * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Log.d("Facebook-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); //conn.setRequestProperty("application/json","multipart/form-data;boundary="+strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); System.out.println("step 1"); conn.connect(); System.out.println("step 2"); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:com.facebook.android.Util.java
/** * Connect to an HTTP URL and return the response as a string. * * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url - the resource to open: must be a welformed URL * @param method - the HTTP method to use ("GET", "POST", etc.) * @param params - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String//from www .j a va 2s . c o m * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ @Deprecated public static String openUrl(String url, String method, Bundle params) throws IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Utility.logd("Facebook-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { Object parameter = params.get(key); if (parameter instanceof byte[]) { dataparams.putByteArray(key, (byte[]) parameter); } } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); try { os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } finally { os.close(); } } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:com.twotoasters.android.hoot.HootTransportHttpUrlConnection.java
@Override public HootResult synchronousExecute(HootRequest request) { if (request.isCancelled()) { return request.getResult(); }/*from w w w .j av a2 s . c o m*/ mStreamingMode = (request.getQueryParameters() == null && request.getData() == null && request.getMultipartEntity() == null) ? StreamingMode.CHUNKED : StreamingMode.FIXED; if (request.getStreamingMode() == HootRequest.STREAMING_MODE_FIXED) { mStreamingMode = StreamingMode.FIXED; } HttpURLConnection connection = null; try { String url = request.buildUri().toString(); Log.v(TAG, "Executing [" + url + "]"); connection = (HttpURLConnection) new URL(url).openConnection(); if (connection instanceof HttpsURLConnection) { HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; httpsConnection.setHostnameVerifier(mSSLHostNameVerifier); } connection.setConnectTimeout(mTimeout); connection.setReadTimeout(mTimeout); synchronized (mConnectionMap) { mConnectionMap.put(request, connection); } setRequestMethod(request, connection); setRequestHeaders(request, connection); if (request.getMultipartEntity() != null) { setMultipartEntity(request, connection); } else if (request.getData() != null) { setRequestData(request, connection); } HootResult hootResult = request.getResult(); hootResult.setResponseCode(connection.getResponseCode()); Log.d(TAG, " - received response code [" + connection.getResponseCode() + "]"); if (request.getResult().isSuccess()) { hootResult.setHeaders(connection.getHeaderFields()); hootResult.setResponseStream(new BufferedInputStream(connection.getInputStream())); } else { hootResult.setResponseStream(new BufferedInputStream(connection.getErrorStream())); } request.deserializeResult(); } catch (Exception e) { request.getResult().setException(e); e.printStackTrace(); } finally { if (connection != null) { synchronized (mConnectionMap) { mConnectionMap.remove(request); } connection.disconnect(); connection = null; } } return request.getResult(); }
From source file:com.ble.facebook.Util.java
public static String posttowall(String url, String method, Bundle params, String Accesstoken) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os;//from www .j ava 2s . co m if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Log.d("Facebook-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } } // use method override if (!params.containsKey("method")) { params.putByteArray("method", method.getBytes()); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(Accesstoken); params.putByteArray("access_token", decoded_token.getBytes()); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); Log.d("OutputStreamedData", ("--" + strBoundary + endLine) + (encodePostBody(params, strBoundary)) + (endLine + "--" + strBoundary + endLine)); os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }