當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpURLConnection.getResponseCode方法代碼示例

本文整理匯總了Java中java.net.HttpURLConnection.getResponseCode方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpURLConnection.getResponseCode方法的具體用法?Java HttpURLConnection.getResponseCode怎麽用?Java HttpURLConnection.getResponseCode使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.net.HttpURLConnection的用法示例。


在下文中一共展示了HttpURLConnection.getResponseCode方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: health

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@Override
public Health health() {
	try {
		URL url =
			new URL("http://greglturnquist.com/learning-spring-boot");
		HttpURLConnection conn =
			(HttpURLConnection) url.openConnection();
		int statusCode = conn.getResponseCode();
		if (statusCode >= 200 && statusCode < 300) {
			return Health.up().build();
		} else {
			return Health.down()
				.withDetail("HTTP Status Code", statusCode)
				.build();
		}
	} catch (IOException e) {
		return Health.down(e).build();
	}
}
 
開發者ID:PacktPublishing,項目名稱:Learning-Spring-Boot-2.0-Second-Edition,代碼行數:20,代碼來源:LearningSpringBootHealthIndicator.java

示例2: AddrCanConnect

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * 鏈接是否可以被請求
 *
 * @param url     地址
 * @param timeout 超時,單位毫秒
 * @return true | false
 */
public static boolean AddrCanConnect(String url, int timeout) {

    if (StringUtil.isEmpty(url)) {
        return false;
    }

    boolean canConnect = false;
    try {
        URL urlStr = new URL(url);

        HttpURLConnection connection = (HttpURLConnection) urlStr.openConnection();
        connection.setUseCaches(false);
        connection.setConnectTimeout(timeout);
        int state = connection.getResponseCode();
        if (state == HttpURLConnection.HTTP_OK) {
            canConnect = true;
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return canConnect;
}
 
開發者ID:DomKing,項目名稱:springbootWeb,代碼行數:31,代碼來源:IPUtil.java

示例3: doGet

import java.net.HttpURLConnection; //導入方法依賴的package包/類
public void doGet(String url) throws Exception{
	URL localURL = new URL(url);
	URLConnection con = openConnection(localURL);
	HttpURLConnection httpCon = (HttpURLConnection)con;
	httpCon.setRequestProperty("Accept-Charset",CHARSET);
	httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	if(httpCon.getResponseCode()>=300){
		throw new RuntimeException("請求失敗...");
	}
	InputStreamReader isr = new InputStreamReader(httpCon.getInputStream());
	BufferedReader reader = new BufferedReader(isr);
	String res = reader.readLine();
	System.out.println(res);
	isr.close();
	reader.close();
}
 
開發者ID:Awesky,項目名稱:awe-awesomesky,代碼行數:17,代碼來源:HttpUtil.java

示例4: handleRedirect

import java.net.HttpURLConnection; //導入方法依賴的package包/類
private static URLConnection handleRedirect(URLConnection urlConnection, int retriesLeft) throws IOException
{
    if (retriesLeft == 0)
    {
        throw new IOException("too many redirects connecting to "+urlConnection.getURL().toString());
    }
    if (urlConnection instanceof HttpURLConnection)
    {
        HttpURLConnection conn = (HttpURLConnection) urlConnection;

        int status = conn.getResponseCode();
        if (status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_SEE_OTHER)
        {
            String newUrl = conn.getHeaderField("Location");
            return handleRedirect(new URL(newUrl).openConnection(), retriesLeft - 1);
        }
    }
    return urlConnection;
}
 
開發者ID:goldmansachs,項目名稱:jrpip,代碼行數:20,代碼來源:Libboot.java

示例5: delete

import java.net.HttpURLConnection; //導入方法依賴的package包/類
public static boolean delete(
        String targetURL,
        String username,
        String password)
        throws IOException
{
    final HttpURLConnection conn = getHttpConnection("DELETE", targetURL, username, password);
    if (null == conn) {
        if (ConstantsUI.DEBUG_MODE) {
            Log.d(ConstantsUI.TAG, "Error get connection object: " + targetURL);
        }
        return false;
    }

    int responseCode = conn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_OK) {
        if (ConstantsUI.DEBUG_MODE) {
            Log.d(
                    ConstantsUI.TAG,
                    "Problem execute delete: " + targetURL + " HTTP response: " + responseCode);
        }
        return false;
    }

    return true;
}
 
開發者ID:nextgis,項目名稱:android_nextgis_mobile,代碼行數:27,代碼來源:NetworkUtil.java

示例6: doInBackground

import java.net.HttpURLConnection; //導入方法依賴的package包/類
protected String doInBackground(Void... urls) {


            try {

                URL url = new URL("https://www.zebapi.com/api/v1/market/ticker/btc/inr");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                res = urlConnection.getResponseCode();

                if (res < 400) {

                    try {
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                        StringBuilder stringBuilder = new StringBuilder();
                        String line;
                        while ((line = bufferedReader.readLine()) != null) {
                            stringBuilder.append(line).append("\n");
                        }
                        System.out.println(stringBuilder);
                        Log.d("Zebpay ", stringBuilder.toString());

                        bufferedReader.close();
                        return stringBuilder.toString();
                    } finally {
                        urlConnection.disconnect();
                    }
                } else {

                    return null;
                }
            } catch (Exception e) {
                Log.e("ERROR", e.getMessage(), e);
                Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();

                return null;


            }
        }
 
開發者ID:someaditya,項目名稱:CoinPryc,代碼行數:41,代碼來源:FifthActivity.java

示例7: send

import java.net.HttpURLConnection; //導入方法依賴的package包/類
private void send() {
    try {
        URL url = getUrl();
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        connection.getResponseCode();
    } catch (Exception ignored) {
    }
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:11,代碼來源:RealmAnalytics.java

示例8: RequestJsonPost

import java.net.HttpURLConnection; //導入方法依賴的package包/類
public static String RequestJsonPost(MsgTO msgto) {
	String json = JSON.toJSONString(msgto);
	String strResponse = null;
	try {
		URL url1 = new URL(msgto.getUrl());
		HttpURLConnection conn = (HttpURLConnection) url1.openConnection();// 建立http連接
		conn.setDoOutput(true);// 設置允許輸出
		conn.setDoInput(true);
		conn.setUseCaches(false);// 設置不用緩存
		conn.setRequestMethod("POST"); // 設置傳遞方式
		conn.setRequestProperty("Connection", "Keep-Alive");// 設置維持長連接
		conn.setRequestProperty("Charset", "UTF-8");// 設置文件字符集
		byte[] data = json.getBytes();// 轉換為字節數組
		conn.setRequestProperty("Content-Length", String.valueOf(data.length));// 設置文件長度
		conn.setRequestProperty("Content-Type", "application/json");// 設置文件類型
		conn.connect(); // 開始連接請求
		OutputStream out = conn.getOutputStream();
		out.write(json.getBytes("utf-8"));// 寫入請求的字符串
		out.flush();
		out.close();
		// System.out.println(conn.getResponseCode());
		// 請求返回的狀態
		if (conn.getResponseCode() == 200) {
			// System.out.println("連接成功");
			InputStream in = conn.getInputStream();// 請求返回的數據
			try {
				byte[] data1 = new byte[in.available()];
				in.read(data1);
				strResponse = new String(data1, "utf-8");// 轉成字符串
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} else {
			System.out.println("no++");
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return strResponse;
}
 
開發者ID:gyp220203,項目名稱:renren-msg,代碼行數:41,代碼來源:HttpPostMsg.java

示例9: getResponse

import java.net.HttpURLConnection; //導入方法依賴的package包/類
private String getResponse(HttpURLConnection connection) throws IOException {
  if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
    throw new RuntimeException(String.format("Something went wrong, server returned: %d (%s)",
        connection.getResponseCode(), connection.getResponseMessage()));
  }

  try (BufferedReader reader = 
      new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
    return reader.lines().collect(Collectors.joining());
  }
}
 
開發者ID:Azure-Samples,項目名稱:SpeechToText-REST,代碼行數:12,代碼來源:SpeechClientREST.java

示例10: patch

import java.net.HttpURLConnection; //導入方法依賴的package包/類
private <T> T patch(UriTemplate template, Object body, final Class<T> modelClass)
        throws IOException, InterruptedException {
    HttpURLConnection connection = (HttpURLConnection) new URL(template.expand()).openConnection();
    withAuthentication(connection);
    setRequestMethodViaJreBugWorkaround(connection, "PATCH");
    byte[] bytes;
    if (body != null) {
        bytes = mapper.writer(new ISO8601DateFormat()).writeValueAsBytes(body);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Content-Length", Integer.toString(bytes.length));
        connection.setDoOutput(true);
    } else {
        bytes = null;
        connection.setDoOutput(false);
    }
    connection.setDoInput(true);

    try {
        connection.connect();
        if (bytes != null) {
            try (OutputStream os = connection.getOutputStream()) {
                os.write(bytes);
            }
        }
        int status = connection.getResponseCode();
        if (status / 100 == 2) {
            if (Void.class.equals(modelClass)) {
                return null;
            }
            try (InputStream is = connection.getInputStream()) {
                return mapper.readerFor(modelClass).readValue(is);
            }
        }
        throw new IOException("HTTP " + status + "/" + connection.getResponseMessage());
    } finally {
        connection.disconnect();
    }
}
 
開發者ID:jenkinsci,項目名稱:gitea-plugin,代碼行數:39,代碼來源:DefaultGiteaConnection.java

示例11: readContentFromPost

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * 發送POST請求,獲取服務器返回結果
 * @param URL
 * @param data
 * @return
 * @throws IOException
 */
private String readContentFromPost(String URL, String data) throws IOException {
	
	gtlog(data);
	URL postUrl = new URL(URL);
	HttpURLConnection connection = (HttpURLConnection) postUrl
			.openConnection();

	connection.setConnectTimeout(2000);// 設置連接主機超時(單位:毫秒)
	connection.setReadTimeout(2000);// 設置從主機讀取數據超時(單位:毫秒)
	connection.setRequestMethod("POST");
	connection.setDoInput(true);
	connection.setDoOutput(true);
	connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	
	// 建立與服務器的連接,並未發送數據
	connection.connect();
	
	 OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(), "utf-8");  
	 outputStreamWriter.write(data);  
	 outputStreamWriter.flush();
	 outputStreamWriter.close();
	
	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";
	}
}
 
開發者ID:Exrick,項目名稱:xmall,代碼行數:50,代碼來源:GeetestLib.java

示例12: execute

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@Async
public void execute(final ScheduleEvent event) {
	int returnCode;
	String body = event.getParameters();
	if(body == null) body = "";
	final String url = getURL(event.getAddressable());

	String method = event.getAddressable().getMethod().toString();

	try {
		if (url == null) {
			logger.info("no address for schedule event " + event.getName());
		} else {
			URL obj = new URL(url);
			HttpURLConnection con = (HttpURLConnection) obj.openConnection();
			con.setRequestMethod(method);
			con.setDoOutput(true);
			con.setConnectTimeout(timeout);
			con.setRequestProperty("Content-Type", "application/json");
			con.setRequestProperty("Content-Length", "" + body.length());
			OutputStream os = con.getOutputStream();
			os.write(body.getBytes());
			returnCode = con.getResponseCode();
			os.close();
			logger.debug("executed event " + event.getId() + " '" + event.getName() + "' response code " + returnCode + " url '" + url + "' body '" + body + "'");
		} 
	} catch (Exception e) {
		logger.error("exception executing event " + event.getId() + " '" + event.getName() + "' url '" + url + "' body '" + body + "' exception " + e.getMessage());
		e.printStackTrace();
	}
}
 
開發者ID:edgexfoundry,項目名稱:device-modbus,代碼行數:32,代碼來源:ScheduleEventHTTPExecutor.java

示例13: downloadIsSeperateBecauseGotoGotRemoved

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * God damn it Gosling, <a href="http://stackoverflow.com/a/4547764/3809164">reference here.</a>
 */
private void downloadIsSeperateBecauseGotoGotRemoved(File downloadTo) throws IOException {
    URL url = new URL(downloadURL);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.addRequestProperty("User-Agent", AGENT);
    connection.connect();
    if (connection.getResponseCode() >= 300 && connection.getResponseCode() < 400) {
        downloadURL = connection.getHeaderField("Location");
        downloadIsSeperateBecauseGotoGotRemoved(downloadTo);
    } else {
        debug(connection.getResponseCode() + " " + connection.getResponseMessage() + " when requesting " + downloadURL);
        copy(connection.getInputStream(), new FileOutputStream(downloadTo));
    }
}
 
開發者ID:ZombieStriker,項目名稱:NeuralNetworkAPI,代碼行數:17,代碼來源:Updater.java

示例14: getPercolationMatches

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * Execute a percolation request for the specified metric
 */
private List<String> getPercolationMatches(JsonMetric jsonMetric) throws IOException {
    HttpURLConnection connection = openConnection("/" + currentIndexName + "/" + jsonMetric.type() + "/_percolate", "POST");
    if (connection == null) {
        LOGGER.error("Could not connect to any configured elasticsearch instances for percolation: {}", Arrays.asList(hosts));
        return Collections.EMPTY_LIST;
    }

    Map<String, Object> data = new HashMap<String, Object>(1);
    data.put("doc", jsonMetric);
    objectMapper.writeValue(connection.getOutputStream(), data);
    closeConnection(connection);

    if (connection.getResponseCode() != 200) {
        throw new RuntimeException("Error percolating " + jsonMetric);
    }

    Map<String, Object> input = objectMapper.readValue(connection.getInputStream(), Map.class);
    List<String> matches = new ArrayList<>();
    if (input.containsKey("matches") && input.get("matches") instanceof List) {
        List<Map<String, String>> foundMatches = (List<Map<String, String>>) input.get("matches");
        for (Map<String, String> entry : foundMatches) {
            if (entry.containsKey("_id")) {
                matches.add(entry.get("_id"));
            }
        }
    }

    return matches;
}
 
開發者ID:oneops,項目名稱:oneops,代碼行數:33,代碼來源:ElasticsearchReporter.java

示例15: testServerNotAvailable

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testServerNotAvailable() throws Exception {
    URL url = new URL(NativeTestServer.getFileURL("/success.txt"));
    HttpURLConnection urlConnection =
            (HttpURLConnection) url.openConnection();
    assertEquals("this is a text file\n", TestUtil.getResponseAsString(urlConnection));
    // After shutting down the server, the server should not be handling
    // new requests.
    NativeTestServer.shutdownNativeTestServer();
    HttpURLConnection secondConnection =
            (HttpURLConnection) url.openConnection();
    // Default implementation reports this type of error in connect().
    // However, since Cronet's wrapper only receives the error in its listener
    // callback when message loop is running, Cronet's wrapper only knows
    // about the error when it starts to read response.
    try {
        secondConnection.getResponseCode();
        fail();
    } catch (IOException e) {
        assertTrue(e instanceof java.net.ConnectException
                || e instanceof UrlRequestException);
        assertTrue((e.getMessage().contains("ECONNREFUSED")
                || (e.getMessage().contains("Connection refused"))
                || e.getMessage().contains("net::ERR_CONNECTION_REFUSED")));
    }
    checkExceptionsAreThrown(secondConnection);
    // Starts the server to avoid crashing on shutdown in tearDown().
    assertTrue(NativeTestServer.startNativeTestServer(getContext()));
}
 
開發者ID:lizhangqu,項目名稱:chromium-net-for-android,代碼行數:32,代碼來源:CronetHttpURLConnectionTest.java


注:本文中的java.net.HttpURLConnection.getResponseCode方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。