List of usage examples for java.net HttpURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:com.gmail.tracebachi.DeltaSkins.Shared.MojangApi.java
public JsonObject getSkin(String uuid) throws IOException, RateLimitedException { HttpURLConnection httpConn = openSkinConnection(uuid); if (httpConn.getResponseCode() == 429) { throw new RateLimitedException(); }/*w w w. j ava 2 s . c om*/ StringWriter writer = new StringWriter(); InputStream inputStream = httpConn.getInputStream(); IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8); String response = writer.toString(); plugin.debugApi("[Response] " + response); synchronized (parserLock) { return parser.parse(response).getAsJsonObject(); } }
From source file:com.example.makerecg.NetworkUtilities.java
/** * Connects to the SampleSync test server, authenticates the provided * username and password.// w w w .j a v a 2 s . co m * This is basically a standard OAuth2 password grant interaction. * * @param username The server account username * @param password The server account password * @return String The authentication token returned by the server (or null) */ public static String authenticate(String username, String password) { String token = null; try { Log.i(TAG, "Authenticating to: " + AUTH_URI); URL urlToRequest = new URL(AUTH_URI); HttpURLConnection conn = (HttpURLConnection) urlToRequest.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("grant_type", "password")); params.add(new BasicNameValuePair("client_id", "CLIENT_ID")); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery(params)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { String response = ""; String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } br.close(); // Response body will look something like this: // { // "token_type": "bearer", // "access_token": "0dd18fd38e84fb40e9e34b1f82f65f333225160a", // "expires_in": 3600 // } JSONObject jresp = new JSONObject(new JSONTokener(response)); token = jresp.getString("access_token"); } else { Log.e(TAG, "Error authenticating"); token = null; } } catch (Exception e) { e.printStackTrace(); } finally { Log.v(TAG, "getAuthtoken completing"); } return token; }
From source file:com.googlesource.gerrit.plugins.its.jira.restapi.JiraRestApi.java
/** * Checks if the connection returned one of the provides pass or fail Codes. If not, an * IOException exception is thrown. If it was part of the list, then the actual response code is * returned. returns true if valid response is returned, otherwise false *///w ww . j a v a 2 s .c o m private boolean validateResponse(HttpURLConnection conn, int passCode, int[] failCodes) throws IOException { responseCode = conn.getResponseCode(); if (responseCode == passCode) { return true; } if ((failCodes == null) || (!ArrayUtils.contains(failCodes, responseCode))) { throw new IOException("Request failed: " + conn.getURL() + " - " + conn.getResponseCode() + " - " + conn.getResponseMessage()); } return false; }
From source file:org.jboss.pnc.buildagent.server.TestGetRunningProcesses.java
@Test public void getRunningProcesses() throws Exception { String terminalUrl = "http://" + HOST + ":" + PORT; HttpURLConnection connection = retrieveProcessList(); Assert.assertEquals(connection.getResponseMessage(), 200, connection.getResponseCode()); JsonNode node = readResponse(connection); Assert.assertEquals(0, node.size()); String context = this.getClass().getName() + ".getRunningProcesses"; ObjectWrapper<Boolean> resultReceived = new ObjectWrapper<>(false); Consumer<TaskStatusUpdateEvent> onStatusUpdate = (statusUpdateEvent) -> { if (statusUpdateEvent.getNewStatus().equals(Status.RUNNING)) { try { HttpURLConnection afterExecution = retrieveProcessList(); Assert.assertEquals(afterExecution.getResponseMessage(), 200, afterExecution.getResponseCode()); JsonNode nodeAfterExecution = readResponse(afterExecution); Assert.assertEquals(1, nodeAfterExecution.size()); resultReceived.set(true); } catch (Exception e) { throw new RuntimeException(e); }/*from www.j a v a 2s. com*/ } }; BuildAgentClient buildAgentClient = new BuildAgentClient(terminalUrl, Optional.empty(), onStatusUpdate, context); buildAgentClient.executeCommand(TEST_COMMAND); Supplier<Boolean> evaluationSupplier = () -> resultReceived.get(); Wait.forCondition(evaluationSupplier, 10, ChronoUnit.SECONDS, "Client was not connected within given timeout."); buildAgentClient.close(); }
From source file:manchester.synbiochem.datacapture.SeekConnector.java
private static Status postForm(HttpURLConnection c, MultipartFormData form) throws IOException { c.setInstanceFollowRedirects(false); c.setDoOutput(true);//w w w .j a v a2s . c o m c.setRequestMethod("POST"); c.setRequestProperty("Content-Type", form.contentType()); c.setRequestProperty("Content-Length", form.length()); c.connect(); try (OutputStream os = c.getOutputStream()) { os.write(form.content()); } return fromStatusCode(c.getResponseCode()); }
From source file:com.bnrc.util.AbFileUtil.java
/** * ????xx.??./*w ww . j a va 2s . c o m*/ * @param connection ? * @return ?? */ public static String getRealFileName(HttpURLConnection connection) { String name = null; try { if (connection == null) { return name; } if (connection.getResponseCode() == 200) { for (int i = 0;; i++) { String mime = connection.getHeaderField(i); if (mime == null) { break; } // "Content-Disposition","attachment; filename=1.txt" // Content-Length if ("content-disposition".equals(connection.getHeaderFieldKey(i).toLowerCase())) { Matcher m = Pattern.compile(".*filename=(.*)").matcher(mime.toLowerCase()); if (m.find()) { return m.group(1).replace("\"", ""); } } } } } catch (Exception e) { e.printStackTrace(); AbLogUtil.e(AbFileUtil.class, "??"); } return name; }
From source file:com.example.trafficvolation_android.VolationWebView.java
public String SearchRequest(String searchString) throws MalformedURLException, IOException { String newFeed = serverAddress + searchString; StringBuilder response = new StringBuilder(); Log.v("gsearch", "url:" + newFeed); URL url = new URL(newFeed); HttpURLConnection httpconn = (HttpURLConnection) url.openConnection(); if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) { BufferedReader input = new BufferedReader(new InputStreamReader(httpconn.getInputStream()), 8129); String strLine = null;/*from w w w . j ava 2s . c o m*/ while ((strLine = input.readLine()) != null) { response.append(strLine); } input.close(); } return response.toString(); }
From source file:com.fidku.geoluks.social.google.AbstractGetNameTask.java
/** * Contacts the user info server to get the profile of the user and extracts the first name * of the user from the profile. In order to authenticate with the user info server the method * first fetches an access token from Google Play services. * @throws IOException if communication with user info server failed. * @throws JSONException if the response from the server could not be parsed. *//* w w w . j a va 2 s.c om*/ private void fetchNameFromProfileServer() throws IOException, JSONException { String token = fetchToken(); if (token == null) { // error has already been handled in fetchToken() return; } URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token); HttpURLConnection con = (HttpURLConnection) url.openConnection(); int sc = con.getResponseCode(); if (sc == 200) { InputStream is = con.getInputStream(); String result = readResponse(is); final JSONObject res = new JSONObject(result); System.out.println(result); String name = getFirstName(result); // mActivity.show(mEmail+" - "+ res.getString("name")+" - "+ res.getString("id")+" - "+ "Google+"); is.close(); mActivity.runOnUiThread(new Runnable() { @Override public void run() { try { mActivity.sessionIniciada(mEmail, res.getString("name"), res.getString("id"), "Google+"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); return; } else if (sc == 401) { GoogleAuthUtil.invalidateToken(mActivity, token); onError("Server auth error, please try again.", null); Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream())); return; } else { onError("Server returned the following error code: " + sc, null); return; } }
From source file:fyp.project.asyncTask.Http_GetPost.java
public void GET(String url, String val) throws IOException { String result = ""; URL url2 = new URL(url + val); HttpURLConnection urlConnection = (HttpURLConnection) url2.openConnection(); int code = urlConnection.getResponseCode(); try {/* ww w. ja v a2 s . c o m*/ if (code == 404) { webpage_output = null; } else { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); result = convertInputStreamToString(in); webpage_output = result; } } catch (Exception e) { Log.d("InputStream", e.getLocalizedMessage()); } finally { urlConnection.disconnect(); } }
From source file:org.exoplatform.utils.image.CookieAwarePicassoDownloader.java
@Override public Response load(Uri uri, int networkPolicy) throws IOException { // TODO use networkPolicy as in com.squareup.picasso.UrlConnectionDownloader // https://github.com/square/picasso/blob/picasso-parent-2.5.2/picasso/src/main/java/com/squareup/picasso/UrlConnectionDownloader.java HttpURLConnection connection = connection(uri); connection.setUseCaches(true);/*www . j a v a 2s . c om*/ int responseCode = connection.getResponseCode(); if (responseCode >= 300) { connection.disconnect(); throw new ResponseException(responseCode + " " + connection.getResponseMessage(), networkPolicy, responseCode); } long contentLength = connection.getHeaderFieldInt("Content-Length", -1); // boolean fromCache = // parseResponseSourceHeader(connection.getHeaderField(RESPONSE_SOURCE)); boolean fromCache = false; return new Response(connection.getInputStream(), fromCache, contentLength); }