Java Code Examples for java.net.httpurlconnection#getResponseCode()

The following examples show how to use java.net.httpurlconnection#getResponseCode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Common.java    From samples with MIT License 6 votes vote down vote up
public static void getApps() {
    try {
        URL obj = new URL("https://api.kobiton.com/v1/apps");
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Authorization", generateBasicAuth());
        int responseCode = con.getResponseCode();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        System.out.println("getApps: " + response.toString());
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }
}
 
Example 2
Source File: HttpUtil.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
/**
 * Makes an HTTP request using GET method to the specified URLand in response it will return Map
 * of status code with get response in String format.
 *
 * @param requestURL the URL of the remote server
 * @param headers the Map <String,String>
 * @return HttpUtilResponse
 * @throws IOException thrown if any I/O error occurred
 */
public static HttpUtilResponse doGetRequest(String requestURL, Map<String, String> headers)
    throws IOException {
  long startTime = System.currentTimeMillis();
  HttpURLConnection httpURLConnection = getRequest(requestURL, headers, startTime);
  HttpUtilResponse response = null;
  String body = "";
  try {
    body = getResponse(httpURLConnection);
  } catch (Exception ex) {
    ProjectLogger.log("Exception occurred while reading body" + ex);
  }
  response = new HttpUtilResponse(body, httpURLConnection.getResponseCode());
  long stopTime = System.currentTimeMillis();
  long elapsedTime = stopTime - startTime;
  ProjectLogger.log(
      "HttpUtil doGetRequest method end at =="
          + stopTime
          + " for requestURL "
          + requestURL
          + " ,Total time elapsed = "
          + elapsedTime,
      LoggerEnum.PERF_LOG);
  return response;
}
 
Example 3
Source File: AsyncHttpResponse.java    From AsyncOkHttpClient with Apache License 2.0 6 votes vote down vote up
/**
    * Perform the connection with the given client
    * and return the response to the relative callback
    * @param connection the connection to execute and collect the informations
    */
void sendResponseMessage(HttpURLConnection connection) {
	String responseBody = null;
	InputStream response = null;
	try {
		int responseCode = connection.getResponseCode();
		if(responseCode >= 300) {
			response = connection.getErrorStream();
			if(response != null) responseBody = Util.inputStreamToString(response);
               sendFailMessage(new HttpRetryException(connection.getResponseMessage(),
                       responseCode), responseBody);
		} else {
			response = connection.getInputStream();
			if(response != null) responseBody = Util.inputStreamToString(response);
			sendSuccessMessage(responseCode, responseBody);
		}
	} catch(IOException e) {
		sendFailMessage(e, (String)null);
	} finally {
		if(response != null) Util.closeQuietly(response);
	}
}
 
Example 4
Source File: IOHelper.java    From Runescape-Web-Walker-Engine with Apache License 2.0 6 votes vote down vote up
public static ServerResponse get(String endpoint, DaxCredentialsProvider daxCredentialsProvider) throws IOException {
    URL myurl = new URL(endpoint);
    HttpURLConnection connection = (HttpsURLConnection) myurl.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);

    connection.setRequestProperty("Method", "GET");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("Accept", "application/json");

    if (daxCredentialsProvider != null) {
        appendAuth(connection, daxCredentialsProvider);
    }

    int responseCode = connection.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_OK) {
        return new ServerResponse(false, connection.getResponseCode(), IOHelper.readInputStream(connection.getErrorStream()));
    }

    String contents = IOHelper.readInputStream(connection.getInputStream());
    return new ServerResponse(true, HttpURLConnection.HTTP_OK, contents);
}
 
Example 5
Source File: SpringWebMvcITest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner commandLineRunner() {
  return new CommandLineRunner() {
    @Override
    public void run(final String ... args) throws Exception {
      final URL obj = new URL("http://localhost:8080");
      final HttpURLConnection connection = (HttpURLConnection)obj.openConnection();
      connection.setRequestMethod("GET");
      final int responseCode = connection.getResponseCode();
      if (200 != responseCode)
        throw new AssertionError("ERROR: response: " + responseCode);
    }
  };
}
 
Example 6
Source File: Method.java    From jlibs with Apache License 2.0 5 votes vote down vote up
private void generatePayload(Path path, QName element) throws Exception{
    if(path.variable()!=null){
        for(Object item: path.resource.getMethodOrResource()){
            if(item instanceof jlibs.wadl.model.Method){
                jlibs.wadl.model.Method method = (jlibs.wadl.model.Method)item;
                if(method.getName().equalsIgnoreCase("GET")){
                    try{
                        HttpURLConnection con = path.execute(method, Collections.<String>emptyList(), null);
                        if(con.getResponseCode()==200){
                            IOUtil.pump(con.getInputStream(), new FileOutputStream(FILE_PAYLOAD), true, true);
                            return;
                        }
                    }catch(Exception ex){
                        ex.printStackTrace();
                    }
                }
            }
        }
    }

    XSInstance xsInstance = new XSInstance();
    InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("xsd-instance.properties");
    if(is!=null)
        xsInstance.loadOptions(CollectionUtil.readProperties(is, null));
    XMLDocument xml = new XMLDocument(new StreamResult(FILE_PAYLOAD), true, 4, null);
    xsInstance.generate(path.getSchema(), element, xml);
}
 
Example 7
Source File: HttpClientTest.java    From gameserver with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
	String host = "192.168.0.77";
	//String host = "charge.babywar.xinqihd.com";
	//URL url = new URL("http://charge.babywar.xinqihd.com/dangle");
	URL url = new URL("http://"+host+":8080/dangle");
	HttpURLConnection conn = (HttpURLConnection)url.openConnection();
	conn.setRequestMethod("POST");
	conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	conn.setReadTimeout(5000);
	conn.setRequestProperty("Host", host);
	conn.setDoInput(true);
	conn.setDoOutput(true);
	OutputStream os = conn.getOutputStream();
	os.write("result=1&uip=1".getBytes());
	os.flush();
	os.close();
	InputStream is = conn.getInputStream();
	BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	String line = null;
	while ((line = reader.readLine()) != null) {
		System.out.println(line);
	}
	reader.close();
	int responseCode = conn.getResponseCode();
	System.out.println(responseCode);
}
 
Example 8
Source File: GeetestLib.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * 发送GET请求,获取服务器返回结果
 * 
 * @param getURL
 * @return 服务器返回结果
 * @throws IOException
 */
private String readContentFromGet(String URL) throws IOException {

	URL getUrl = new URL(URL);
	HttpURLConnection connection = (HttpURLConnection) getUrl
			.openConnection();

	connection.setConnectTimeout(2000);// 设置连接主机超时(单位:毫秒)
	connection.setReadTimeout(2000);// 设置从主机读取数据超时(单位:毫秒)

	// 建立与服务器的连接,并未发送数据
	connection.connect();
	
	if (connection.getResponseCode() == 200) {
		// 发送数据到服务器并使用Reader读取返回的数据
		StringBuffer sBuffer = new StringBuffer();

		InputStream inStream = null;
		byte[] buf = new byte[1024];
		inStream = connection.getInputStream();
		for (int n; (n = inStream.read(buf)) != -1;) {
			sBuffer.append(new String(buf, 0, n, "UTF-8"));
		}
		inStream.close();
		connection.disconnect();// 断开连接
           
		return sBuffer.toString();	
	}
	else {
		
		return "fail";
	}
}
 
Example 9
Source File: HistoryServerTest.java    From flink with Apache License 2.0 5 votes vote down vote up
public static String getFromHTTP(String url) throws Exception {
	URL u = new URL(url);
	HttpURLConnection connection = (HttpURLConnection) u.openConnection();
	connection.setConnectTimeout(100000);
	connection.connect();
	InputStream is;
	if (connection.getResponseCode() >= 400) {
		// error!
		is = connection.getErrorStream();
	} else {
		is = connection.getInputStream();
	}

	return IOUtils.toString(is, connection.getContentEncoding() != null ? connection.getContentEncoding() : "UTF-8");
}
 
Example 10
Source File: TenpayHttpClient.java    From jframe with Apache License 2.0 5 votes vote down vote up
/**
 * get方式处理
 * 
 * @param conn
 * @throws IOException
 */
protected void doGet(HttpURLConnection conn) throws IOException {

    // 以GET方式通信
    conn.setRequestMethod("GET");

    // 设置请求默认属性
    this.setHttpRequest(conn);

    // 获取响应返回状态码
    this.responseCode = conn.getResponseCode();

    // 获取应答输入流
    this.inputStream = conn.getInputStream();
}
 
Example 11
Source File: AvaticaHttpClientImpl.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
public byte[] send(byte[] request) {
  // TODO back-off policy?
  while (true) {
    try {
      final HttpURLConnection connection = openConnection();
      connection.setRequestMethod("POST");
      connection.setDoInput(true);
      connection.setDoOutput(true);
      try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
        wr.write(request);
        wr.flush();
        wr.close();
      }
      final int responseCode = connection.getResponseCode();
      final InputStream inputStream;
      if (responseCode == HttpURLConnection.HTTP_UNAVAILABLE) {
        // Could be sitting behind a load-balancer, try again.
        continue;
      } else if (responseCode != HttpURLConnection.HTTP_OK) {
        inputStream = connection.getErrorStream();
        if (inputStream == null) {
          // HTTP Transport exception that resulted in no content coming back
          throw new RuntimeException("Failed to read data from the server: HTTP/" + responseCode);
        }
      } else {
        inputStream = connection.getInputStream();
      }
      return AvaticaUtils.readFullyToBytes(inputStream);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}
 
Example 12
Source File: IIIFUtils.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
public static int checkIiifApi (final URL url) throws IOException {
	URL validationUrl = new URL("https://iiif.io/api/presentation/validator/service/validate?format=json&version=2.1&url="+url.toString());
	HttpURLConnection con = (HttpURLConnection) validationUrl.openConnection();
	con.addRequestProperty("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:74.0) Gecko/20100101 Firefox/74.0");
	con.setRequestMethod("GET");	
	return con.getResponseCode();
}
 
Example 13
Source File: NetworkAccess.java    From wallpaper with GNU General Public License v2.0 5 votes vote down vote up
/**
 * http request
 * 
 * @param requestUrl
 * @param params
 * @return
 */
public NetworkResponse httpRequest(String requestUrl, Map<?, ?> params) {
	HttpURLConnection connection = null;
	final NetworkResponse networkResponse = new NetworkResponse();

	if (HttpURLConnectionHelper.currentRequestMethod.equals(HttpURLConnectionHelper.REQUEST_METHOD_TYPE_GET)) {
		connection = HttpURLConnectionHelper.getHttpURLConnectionWithGet(requestUrl, params);
	} else {
		connection = HttpURLConnectionHelper.getHttpURLConnectionWithPost(requestUrl, params);
	}
	// set header information
	if (null == mProtocolHandler) {
		mProtocolHandler = ProtocolHandler.defaultRequestHandler();
	}
	mProtocolHandler.handleRequest(connection);

	// get data from network
	try {
		if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
			String responseString = HttpURLConnectionHelper.getHttpResponseString(connection);
			networkResponse.statusCode = HttpURLConnection.HTTP_OK;
			networkResponse.data = responseString;
			LogUtils.d("kyson", "Response:" + responseString);
		} else {
			LogUtils.d("HttpError", connection.getResponseCode() + ":" + connection.getResponseMessage());
			networkResponse.statusCode = connection.getResponseCode();
			networkResponse.codeDesc = connection.getResponseMessage();
			networkResponse.data = "";
		}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		connection.disconnect();
		connection = null;
		e.printStackTrace();
	}

	return networkResponse;
}
 
Example 14
Source File: PaymentCardShenZhouFu.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public PaymentResult doPost(String userName) {
	try {
		PaymentResult result = new PaymentResult();

		URL url = new URL(getUrl());
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		urlConn.setRequestMethod("POST");
		urlConn.setDoInput(true);
		urlConn.setDoOutput(true);
		OutputStream os = urlConn.getOutputStream();
		os.write(getPostString(userName).getBytes());
		os.close();

		result.statusCode = urlConn.getResponseCode();

		if (result.statusCode == 200) {
			InputStream is = urlConn.getInputStream();
			ByteArrayOutputStream baos = new ByteArrayOutputStream(3);
			int ch = is.read();
			while ( ch != -1 ) {
				baos.write(ch);
				ch = is.read();
			}
			result.code = new String(baos.toByteArray());
			return result;
		} else {
			return result;
		}
	} catch (Exception e) {
		e.printStackTrace();
	}

	return null;
}
 
Example 15
Source File: CaMgmtClient.java    From xipki with Apache License 2.0 4 votes vote down vote up
private byte[] transmit(MgmtAction action, MgmtRequest req, boolean voidReturn)
    throws CaMgmtException {
  initIfNotDone();

  byte[] reqBytes = req == null ? null : JSON.toJSONBytes(req);
  int size = reqBytes == null ? 0 : reqBytes.length;

  URL url = actionUrlMap.get(action);

  try {
    HttpURLConnection httpUrlConnection = IoUtil.openHttpConn(url);

    if (httpUrlConnection instanceof HttpsURLConnection) {
      if (sslSocketFactory != null) {
        ((HttpsURLConnection) httpUrlConnection).setSSLSocketFactory(sslSocketFactory);
      }
      if (hostnameVerifier != null) {
        ((HttpsURLConnection) httpUrlConnection).setHostnameVerifier(hostnameVerifier);
      }
    }

    httpUrlConnection.setDoOutput(true);
    httpUrlConnection.setUseCaches(false);

    httpUrlConnection.setRequestMethod("POST");
    httpUrlConnection.setRequestProperty("Content-Type", REQUEST_CT);
    httpUrlConnection.setRequestProperty("Content-Length", java.lang.Integer.toString(size));
    OutputStream outputstream = httpUrlConnection.getOutputStream();
    if (size != 0) {
      outputstream.write(reqBytes);
    }
    outputstream.flush();

    if (httpUrlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
      InputStream in = httpUrlConnection.getInputStream();

      boolean inClosed = false;
      try {
        String responseContentType = httpUrlConnection.getContentType();
        if (!RESPONSE_CT.equals(responseContentType)) {
          throw new CaMgmtException(
              "bad response: mime type " + responseContentType + " not supported!");
        }

        if (voidReturn) {
          return null;
        } else {
          inClosed = true;
          return IoUtil.read(httpUrlConnection.getInputStream());
        }
      } finally {
        if (in != null & !inClosed) {
          in.close();
        }
      }
    } else {
      String errorMessage = httpUrlConnection.getHeaderField(HttpConstants.HEADER_XIPKI_ERROR);
      if (errorMessage == null) {
        StringBuilder sb = new StringBuilder(100);
        sb.append("server returns ").append(httpUrlConnection.getResponseCode());
        String respMsg = httpUrlConnection.getResponseMessage();
        if (StringUtil.isNotBlank(respMsg)) {
          sb.append(" ").append(respMsg);
        }
        throw new CaMgmtException(sb.toString());
      } else {
        throw new CaMgmtException(errorMessage);
      }
    }
  } catch (IOException ex) {
    throw new CaMgmtException(
        "IOException while sending message to the server: " + ex.getMessage(), ex);
  }
}
 
Example 16
Source File: Http.java    From OpenMemories-AppStore with MIT License 4 votes vote down vote up
private static Response toResponse(HttpURLConnection connection) throws IOException {
    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
        throw new IOException("HTTP error " + connection.getResponseCode() + " (" + connection.getResponseMessage() + ")");
    return new Response(connection);
}
 
Example 17
Source File: HurlStack.java    From SaveVolley with Apache License 2.0 4 votes vote down vote up
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    SaveProtocolVersion saveProtocolVersion = HurlProtocolVersionAdapter.getInstance()
            .adaptiveProtocolVersion(null);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    SaveStatusLine responseStatus = HurlStatusLineAdapter.getInstance()
            .adaptiveStatusLine(
                    HurlProtocolVersionAdapter.getInstance(),
                    connection);
    SaveHttpResponse saveHttpResponse = new SaveHttpResponse(responseStatus);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        saveHttpResponse.setEntity(
                HurlHttpEntityAdapter.getInstance().adaptiveEntity(connection));
    }
    HurlHeaderAdapter.getInstance().adaptiveHeader(saveHttpResponse, connection);
    return saveHttpResponse;
}
 
Example 18
Source File: SimpleHttpInvokerRequestExecutor.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * Validate the given response as contained in the HttpURLConnection object,
 * throwing an exception if it does not correspond to a successful HTTP response.
 * <p>Default implementation rejects any HTTP status code beyond 2xx, to avoid
 * parsing the response body and trying to deserialize from a corrupted stream.
 * @param config the HTTP invoker configuration that specifies the target service
 * @param con the HttpURLConnection to validate
 * @throws IOException if validation failed
 * @see java.net.HttpURLConnection#getResponseCode()
 */
protected void validateResponse(HttpInvokerClientConfiguration config, HttpURLConnection con)
		throws IOException {

	if (con.getResponseCode() >= 300) {
		throw new IOException(
				"Did not receive successful HTTP response: status code = " + con.getResponseCode() +
				", status message = [" + con.getResponseMessage() + "]");
	}
}
 
Example 19
Source File: BaseImageDownloader.java    From candybar with Apache License 2.0 2 votes vote down vote up
/**
 * @param conn Opened request connection (response code is available)
 * @return <b>true</b> - if data from connection is correct and should be read and processed;
 * <b>false</b> - if response contains irrelevant data and shouldn't be processed
 * @throws IOException
 */
protected boolean shouldBeProcessed(HttpURLConnection conn) throws IOException {
    return conn.getResponseCode() == 200;
}
 
Example 20
Source File: InterceptorTestBase.java    From msf4j with Apache License 2.0 2 votes vote down vote up
/**
 * @param path      http path
 * @param keepAlive should the connection be kept alive
 * @param headers   createHttpUrlConnection headers
 * @return object from response
 * @throws IOException on any exception
 */
protected int doGetAndGetStatusCode(String path, boolean keepAlive, Map<String, String> headers)
        throws IOException {
    HttpURLConnection urlConn = createHttpUrlConnection(path, HttpMethod.GET, keepAlive, headers);
    return urlConn.getResponseCode();
}