当前位置: 首页>>代码示例>>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;未经允许,请勿转载。