List of usage examples for java.net HttpURLConnection getErrorStream
public InputStream getErrorStream()
From source file:karroo.app.test.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//from w ww . ja v a 2 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) { if (params.get(key) instanceof byte[]) { 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.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); 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.denimgroup.threadfix.service.defects.utils.RestUtilsImpl.java
@Nonnull private InputStream postUrl(String urlString, String data, String username, String password, String contentType) {/*from ww w. j av a2 s . c o m*/ URL url; try { url = new URL(urlString); } catch (MalformedURLException e) { LOG.warn("URL used for POST was bad: '" + urlString + "'"); throw new RestUrlException(e, "Received a malformed server URL."); } HttpURLConnection httpConnection = null; OutputStreamWriter outputWriter = null; try { if (proxyService == null) { httpConnection = (HttpURLConnection) url.openConnection(); } else { httpConnection = proxyService.getConnectionWithProxyConfig(url, classToProxy); } setupAuthorization(httpConnection, username, password); httpConnection.addRequestProperty("Content-Type", contentType); httpConnection.addRequestProperty("Accept", contentType); httpConnection.setDoOutput(true); outputWriter = new OutputStreamWriter(httpConnection.getOutputStream()); outputWriter.write(data); outputWriter.flush(); InputStream is = httpConnection.getInputStream(); return is; } catch (IOException e) { LOG.warn("IOException encountered trying to post to URL with message: " + e.getMessage()); if (httpConnection == null) { LOG.warn( "HTTP connection was null so we cannot do further debugging of why the HTTP request failed"); } else { try { InputStream errorStream = httpConnection.getErrorStream(); if (errorStream == null) { LOG.warn("Error stream from HTTP connection was null"); } else { LOG.warn( "Error stream from HTTP connection was not null. Attempting to get response text."); setPostErrorResponse(IOUtils.toString(errorStream)); LOG.warn("Error text in response was '" + getPostErrorResponse() + "'"); throw new RestIOException(e, getPostErrorResponse(), "Unable to get response from server. Error text was: " + getPostErrorResponse(), getStatusCode(httpConnection)); } } catch (IOException e2) { LOG.warn("IOException encountered trying to read the reason for the previous IOException: " + e2.getMessage(), e2); throw new RestIOException(e2, "Unable to read response from server." + e2.getMessage(), getStatusCode(httpConnection)); } } throw new RestIOException(e, "Unable to read response from server." + e.toString()); } finally { if (outputWriter != null) { try { outputWriter.close(); } catch (IOException e) { LOG.warn("Failed to close output stream in postUrl.", e); } } } }
From source file:org.whispersystems.textsecure.internal.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;/*from w w w. j a va 2 s. co 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: MismatchedDevices mismatchedDevices; try { response = Util.readFully(connection.getErrorStream()); mismatchedDevices = JsonUtil.fromJson(response, MismatchedDevices.class); } catch (JsonProcessingException e) { Log.w(TAG, e); throw new NonSuccessfulResponseCodeException( "Bad response: " + responseCode + " " + responseMessage); } catch (IOException e) { throw new PushNetworkException(e); } throw new MismatchedDevicesException(mismatchedDevices); case 410: StaleDevices staleDevices; try { response = Util.readFully(connection.getErrorStream()); staleDevices = JsonUtil.fromJson(response, StaleDevices.class); } catch (JsonProcessingException e) { throw new NonSuccessfulResponseCodeException( "Bad response: " + responseCode + " " + responseMessage); } catch (IOException e) { throw new PushNetworkException(e); } throw new StaleDevicesException(staleDevices); case 411: DeviceLimit deviceLimit; try { response = Util.readFully(connection.getErrorStream()); deviceLimit = JsonUtil.fromJson(response, DeviceLimit.class); } catch (JsonProcessingException e) { throw new NonSuccessfulResponseCodeException( "Bad response: " + responseCode + " " + responseMessage); } catch (IOException e) { throw new PushNetworkException(e); } throw new DeviceLimitExceededException(deviceLimit); case 417: throw new ExpectationFailedException(); } if (responseCode != 200 && responseCode != 204) { throw new NonSuccessfulResponseCodeException("Bad response: " + responseCode + " " + responseMessage); } return connection; }
From source file:com.mobli.android.Util.java
/** * Connect to an HTTP URL and return the response as a string. * /*from w w w .j a v a 2s . co m*/ * 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 * @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); } Util.logd("Mobli-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " MobliAndroidSDK"); 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()); 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 Mobli error response = read(conn.getErrorStream()); } return response; }
From source file:com.bpd.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//from w ww. j a v a2s .co 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; // Try to get filename key String filename = params.getString("filename"); // If found if (filename != null) { // Remove from params params.remove("filename"); } 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.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); 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=\"" + ((filename != null) ? 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:net.bashtech.geobot.BotManager.java
public static String postRemoteDataSongRequest(String urlString, String channel, String requester) { if (BotManager.getInstance().CoeBotTVAPIKey.length() > 4) { URL url;//from w w w. j a v a2 s . c o m HttpURLConnection conn; try { url = new URL("http://coebot.tv/api/v1/reqsongs/add/" + channel.toLowerCase() + "$" + BotManager.getInstance().CoeBotTVAPIKey + "$" + BotManager.getInstance().nick); String postData = "url=" + URLEncoder.encode(urlString, "UTF-8") + "&requestedBy=" + URLEncoder.encode(requester, "UTF-8"); conn = (HttpURLConnection) url.openConnection(); System.out.println(postData); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "CoeBot"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length)); // conn.setConnectTimeout(5 * 1000); // conn.setReadTimeout(5 * 1000); PrintWriter out = new PrintWriter(conn.getOutputStream()); out.print(postData); out.close(); String response = ""; if (conn.getResponseCode() < 400) { Scanner inStream = new Scanner(conn.getInputStream()); while (inStream.hasNextLine()) { response += (inStream.nextLine()); } inStream.close(); } else { Scanner inStream = new Scanner(conn.getErrorStream()); while (inStream.hasNextLine()) { response += (inStream.nextLine()); } inStream.close(); } System.out.println(response); return response; } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } return null; } else { return null; } }
From source file:com.niroshpg.android.gmail.CronHandlerServlet.java
public BigInteger getHistoryIdXX(Gmail service, String userId, Credential credential) throws IOException { BigInteger historyId = null;//from w w w . jav a 2 s . c om try { URL url = new URL("https://www.googleapis.com/gmail/v1/users/" + userId + "/profile"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //credential.refreshToken(); connection.setRequestProperty("Authorization", "Bearer " + credential.getAccessToken()); connection.setRequestProperty("Content-Type", "application/json"); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { // OK BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer res = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { res.append(line); logger.warning(line); } reader.close(); JSONObject jsonObj = new JSONObject(res); historyId = BigInteger.valueOf(jsonObj.getLong("historyId")); } else { // Server returned HTTP error code. logger.warning("failed : " + connection.getResponseCode()); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String error = ""; String text; while ((text = br.readLine()) != null) { error += text; } logger.warning("error : " + error); } } catch (Exception e) { logger.warning("exception : " + e.getMessage() + " , " + e.getStackTrace().toString()); } return historyId; }
From source file:com.sample.facebook.Util.java
/** * Connect to an HTTP URL and return the response as a string. * /*from w w w . j a v a 2 s .c o m*/ * 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 * @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); //url+="&fields=email"; 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.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setConnectTimeout(45000); conn.connect(); 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:jp.go.nict.langrid.servicecontainer.executor.jsonrpc.DynamicJsonRpcServiceExecutor.java
@Override public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable { Map<String, Object> mimeHeaders = new HashMap<String, Object>(); final List<RpcHeader> rpcHeaders = new ArrayList<RpcHeader>(); Pair<Endpoint, Long> r = preprocessJsonRpc(mimeHeaders, rpcHeaders); Endpoint ep = r.getFirst();/*from w ww . j a va 2 s. c om*/ long s = System.currentTimeMillis(); HttpURLConnection con = null; JsonRpcResponse ret = null; RpcFault fault = null; try { con = (HttpURLConnection) ep.getAddress().toURL().openConnection(); con.setUseCaches(false); con.setDoOutput(true); con.setConnectTimeout(3000); con.setReadTimeout(10000); con.setRequestProperty("Accept", "application/json-rpc"); con.setRequestProperty("Content-type", "application/json-rpc"); con.setRequestProperty(LangridConstants.HTTPHEADER_PROTOCOL, Protocols.JSON_RPC); String authUserName = ep.getUserName(); String authPassword = ep.getPassword(); if (authUserName != null && authUserName.length() > 0) { String header = authUserName + ":" + ((authPassword != null) ? authPassword : ""); con.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(header.getBytes()))); } for (Map.Entry<String, Object> entry : mimeHeaders.entrySet()) { con.addRequestProperty(entry.getKey(), entry.getValue().toString()); } OutputStream os = con.getOutputStream(); JSON.encode(JsonRpcUtil.createRequest(rpcHeaders, method, args), os); os.flush(); InputStream is = null; try { is = con.getInputStream(); } catch (IOException e) { is = con.getErrorStream(); } finally { if (is != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); is = new DuplicatingInputStream(is, baos); try { ret = JSON.decode(is, JsonRpcResponse.class); } catch (JSONException e) { fault = new RpcFault("Server.userException", e.toString(), ExceptionUtil.getMessageWithStackTrace(e) + "\nsource: " + new String(baos.toByteArray(), "UTF-8")); } } else { throw new RuntimeException("failed to open response stream."); } } if (ret.getError() != null) { fault = ret.getError(); throw RpcFaultUtil.rpcFaultToThrowable(ret.getError()); } return converter.convert(ret.getResult(), method.getReturnType()); } finally { long dt = System.currentTimeMillis() - s; List<RpcHeader> resHeaders = null; if (ret != null && ret.getHeaders() != null) { resHeaders = Arrays.asList(ret.getHeaders()); } postprocessJsonRpc(r.getSecond(), dt, con, resHeaders, fault); if (con != null) con.disconnect(); } }
From source file:com.mycompany.grupo6ti.GenericResource.java
@DELETE @Produces("application/json") @Path("/anularOc/{id}/{motivo}") public String anularOc(@PathParam("id") String id, @PathParam("motivo") String motivo) { try {//from w w w . j a v a 2s . c om URL url = new URL("http://localhost:83/anular/" + id); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream is; conn.setRequestProperty("Accept-Charset", "UTF-8"); conn.setRequestProperty("Content-Type", "application/json"); conn.setUseCaches(true); //conn.setRequestMethod("DELETE"); conn.setRequestMethod("POST"); // We have to override the post method so we can send data conn.setRequestProperty("X-HTTP-Method-Override", "DELETE"); conn.setDoOutput(true); conn.setDoInput(true); String idJson = "{\n" + " \"anulacion\": \"" + motivo + "\"\n" + "}"; //String idJson2 = "[\"Test\", \"Funcionando Bien\"]"; OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write(idJson); 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(); return ("[\"Test\", \"Funcionando Bien1\"]"); } catch (Exception e) { e.printStackTrace(); return ("[\"Test\", \"Funcionando Bien2\"]"); } }