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


Java URLConnection.setRequestProperty方法代碼示例

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


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

示例1: checkRedirect

import java.net.URLConnection; //導入方法依賴的package包/類
private static URLConnection checkRedirect(URLConnection conn, int timeout) throws IOException {
    if (conn instanceof HttpURLConnection) {
        conn.connect();
        int code = ((HttpURLConnection) conn).getResponseCode();
        if (code == HttpURLConnection.HTTP_MOVED_TEMP
                || code == HttpURLConnection.HTTP_MOVED_PERM) {
            // in case of redirection, try to obtain new URL
            String redirUrl = conn.getHeaderField("Location"); //NOI18N
            if (null != redirUrl && !redirUrl.isEmpty()) {
                //create connection to redirected url and substitute original conn
                URL redirectedUrl = new URL(redirUrl);
                URLConnection connRedir = redirectedUrl.openConnection();
                // XXX is this neede
                connRedir.setRequestProperty("User-Agent", "NetBeans"); // NOI18N
                connRedir.setConnectTimeout(timeout);
                connRedir.setReadTimeout(timeout);
                if (connRedir instanceof HttpsURLConnection) {
                    NetworkAccess.initSSL((HttpsURLConnection) connRedir);
                }
                return connRedir;
            }
        }
    }
    return conn;
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:26,代碼來源:NetworkAccess.java

示例2: getJarFile

import java.net.URLConnection; //導入方法依賴的package包/類
private JarFile getJarFile(URL url) throws IOException {
    // Optimize case where url refers to a local jar file
    if (isOptimizable(url)) {
        //HACK
        //FileURLMapper p = new FileURLMapper (url);
        File p = new File(url.getPath());

        if (!p.exists()) {
            throw new FileNotFoundException(p.getPath());
        }
        return new JarFile (p.getPath());
    }
    URLConnection uc = getBaseURL().openConnection();
    uc.setRequestProperty(USER_AGENT_JAVA_VERSION, JAVA_VERSION);
    return ((JarURLConnection)uc).getJarFile();
}
 
開發者ID:tranleduy2000,項目名稱:javaide,代碼行數:17,代碼來源:URLClassPath.java

示例3: load

import java.net.URLConnection; //導入方法依賴的package包/類
public TemplateLoader load()
{
    try
    {
        URLConnection urlConnection = new URL(url).openConnection();
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
        urlConnection.setUseCaches(false);
        urlConnection.connect();
        Files.copy(urlConnection.getInputStream(), Paths.get(dest));
        ((HttpURLConnection)urlConnection).disconnect();
    } catch (IOException e)
    {
        e.printStackTrace();
    }
    return this;
}
 
開發者ID:Dytanic,項目名稱:CloudNet,代碼行數:17,代碼來源:TemplateLoader.java

示例4: downloadFile

import java.net.URLConnection; //導入方法依賴的package包/類
/**
 * 下載文件
 * 
 * @param urlString
 * @return
 * @throws Exception
 */
public static String downloadFile(String urlString) throws Exception {

    URL url = new URL(urlString);
    URLConnection con = url.openConnection();
    con.setConnectTimeout(30 * 1000);
    con.setRequestProperty("Charset", "UTF-8");

    InputStream is = con.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    StringBuilder fileContent = new StringBuilder();
    // 開始讀取
    String line;
    while ((line = br.readLine()) != null) {
        fileContent.append(new String(line.getBytes(), "UTF-8"));
        fileContent.append(System.getProperty("line.separator"));
    }
    // 完畢,關閉所有鏈接
    is.close();
    br.close();

    return fileContent.toString();
}
 
開發者ID:uavorg,項目名稱:uavstack,代碼行數:31,代碼來源:IOHelper.java

示例5: getViewersNum

import java.net.URLConnection; //導入方法依賴的package包/類
/**
 * Get the viewers on that stream
 * @return the number of viewers seeing the stream
 */
public final int getViewersNum() {
	if (!this.isLive()) return 0;
	try {
		URL url = new URL("https://api.twitch.tv/kraken/streams/" + channel.substring(1));
		URLConnection conn = url.openConnection();
		conn.setRequestProperty("Client-ID", bot.getClientID());
        BufferedReader br = new BufferedReader( new InputStreamReader( conn.getInputStream() ));
        JsonObject jsonObj = JsonObject.readFrom(br.readLine());
        int i = jsonObj.get("stream").asObject().get("viewers").asInt();
        return i;
	} catch (IOException ex) {
		return 0;
	}
}
 
開發者ID:artek2001,項目名稱:twichat,代碼行數:19,代碼來源:Channel.java

示例6: createConnectionToURL

import java.net.URLConnection; //導入方法依賴的package包/類
/**
 * Create URLConnection instance.
 *
 * @param url            to what url
 * @param requestHeaders additional request headers
 * @return connection instance
 * @throws IOException when url is invalid or failed to establish connection
 */
public static URLConnection createConnectionToURL(final String url, final Map<String, String> requestHeaders) throws IOException {
    final URL connectionURL = URLUtility.stringToUrl(url);
    if (connectionURL == null) {
        throw new IOException("Invalid url format: " + url);
    }

    final URLConnection urlConnection = connectionURL.openConnection();
    urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
    urlConnection.setReadTimeout(READ_TIMEOUT);

    if (requestHeaders != null) {
        for (final Map.Entry<String, String> entry : requestHeaders.entrySet()) {
            urlConnection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }

    return urlConnection;
}
 
開發者ID:SUTFutureCoder,項目名稱:localcloud_fe,代碼行數:27,代碼來源:URLConnectionHelper.java

示例7: queueSong

import java.net.URLConnection; //導入方法依賴的package包/類
/**
 * Queues song for the audio player
 * @param player main instance of the AudioPlayer
 * @param event event triggered when command is sent
 * @param audioLink URL linking to audio file
 * @throws IOException thrown if connection could not be made
 * @throws UnsupportedAudioFileException thrown if audio file linked
 *                                       is not playable
 */
private synchronized void queueSong(AudioPlayer player,
                       MessageReceivedEvent event,
                       String audioLink)
        throws IOException, UnsupportedAudioFileException {
    //Connection to server for music file
    //might be rejected because of no user agent
    URLConnection conn = new URL(audioLink.trim()).openConnection();
    conn.setRequestProperty("User-Agent", rexCord.USER_AGENT);
    AudioInputStream audioInputStream
            = AudioSystem.getAudioInputStream(conn.getInputStream());

    player.queue(audioInputStream);
    String message
            = String.format(
            "Song is now queued! Your song is #%d on the queue.",
            player.getPlaylistSize());
    rexCord.sendMessage(event.getChannel(), message);


    //Start playing music if there is nothing in the playlist.
    if (player.getPlaylistSize() == 0) {
        player.provide();
    }
}
 
開發者ID:Pedro12909,項目名稱:RexCord,代碼行數:34,代碼來源:PlayCommand.java

示例8: createInputStream

import java.net.URLConnection; //導入方法依賴的package包/類
@Override
public InputStream createInputStream(final URI uri, final Map<?, ?> options) throws IOException {
    try
    {
        URL url = new URL(uri.toString());
        final URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Accept", acceptedContentTypes);
        int timeout = getTimeout(options);
        if (timeout != 0)
        {
            urlConnection.setConnectTimeout(timeout);
            urlConnection.setReadTimeout(timeout);
        }
        InputStream result = urlConnection.getInputStream();
        Map<Object, Object> response = getResponse(options);
        if (response != null)
        {
            response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, urlConnection.getLastModified());
        }
        return result;
    }
    catch (RuntimeException exception)
    {
        throw new Resource.IOWrappedException(exception);
    }

}
 
開發者ID:vrapio,項目名稱:rest-modeling-framework,代碼行數:28,代碼來源:ContentNegotiationURIHandler.java

示例9: jsonQuery

import java.net.URLConnection; //導入方法依賴的package包/類
public Object jsonQuery(String postfix) throws IOException {
    URL url = new URL(SITE_PREFIX + spigetId + postfix);
    URLConnection conn = url.openConnection();
    conn.setRequestProperty("User-Agent", USER_AGENT);
    if(((HttpURLConnection)conn).getResponseCode() == 404)
        return null;
    return JSONValue.parse(new InputStreamReader((InputStream)conn.getContent()));
}
 
開發者ID:upperlevel,項目名稱:uppercore,代碼行數:9,代碼來源:SpigetUpdateChecker.java

示例10: post

import java.net.URLConnection; //導入方法依賴的package包/類
public static final byte[] post(String url, String data, Map<String, String> headers) {
	try {
		URLConnection conn = new URL(url).openConnection();
		conn.setDoOutput(true);

		if (headers != null) {
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				conn.setRequestProperty(entry.getKey(), entry.getValue());
			}
		}
		OutputStream os = conn.getOutputStream();
		OutputStreamWriter wr = new OutputStreamWriter(os);
		wr.write(data);
		wr.flush();
		wr.close();
		os.close();
		System.out.println("HTTP Response headers: " + conn.getHeaderFields());
		List<String> header = conn.getHeaderFields().get("Content-Disposition");
		if (header != null && header.size() > 0) {
			headers.put("Content-Disposition", header.get(0));
		}
		header = conn.getHeaderFields().get("Content-Type");
		if (header != null && header.size() > 0) {
			headers.put("Content-Type", header.get(0));
		}
		InputStream is = conn.getInputStream();
		byte[] result = IOUtils.toByteArray(is);
		is.close();
		return result;
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
開發者ID:21ca,項目名稱:selenium-testng-template,代碼行數:34,代碼來源:HttpUtils.java

示例11: post

import java.net.URLConnection; //導入方法依賴的package包/類
public String post(String url, String params) {
	String result = "";
	try {
		URL realUrl = new URL(url);
		// 打開和URL之間的連接
		URLConnection conn = realUrl.openConnection();
		// 設置通用的請求屬性
		conn.setRequestProperty("accept", "*/*");
		conn.setRequestProperty("connection", "Keep-Alive");
		// conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;
		// MSIE 6.0; Windows NT 5.1;SV1)");
		// 發送POST請求必須設置如下兩行
		conn.setDoOutput(true);
		conn.setDoInput(true);

		// 獲取URLConnection對象對應的輸出流
		try (PrintWriter out = new PrintWriter(conn.getOutputStream())) {
			// 發送請求參數
			out.print(params);
			// flush輸出流的緩衝
			out.flush();
		}

		// 定義BufferedReader輸入流來讀取URL的響應
		try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		}
	} catch (Exception e) {
		throw new ZhhrUtilException("發送POST請求出現異常!原因:" + e.getMessage());
	}
	return result;
}
 
開發者ID:wooui,項目名稱:springboot-training,代碼行數:36,代碼來源:HttpUtil.java

示例12: getAudioFileFormat

import java.net.URLConnection; //導入方法依賴的package包/類
/**
 * Returns AudioFileFormat from URL.
 */
public AudioFileFormat getAudioFileFormat(URL url)
		throws UnsupportedAudioFileException, IOException
{
	if (TDebug.TraceAudioFileReader)
	{
		TDebug.out("MpegAudioFileReader.getAudioFileFormat(URL): begin");
	}
	long lFileLengthInBytes = AudioSystem.NOT_SPECIFIED;
	URLConnection conn = url.openConnection();
	// Tell shoucast server (if any) that SPI support shoutcast stream.
	conn.setRequestProperty("Icy-Metadata", "1");
	InputStream inputStream = conn.getInputStream();
	AudioFileFormat audioFileFormat = null;
	try
	{
		audioFileFormat = getAudioFileFormat(inputStream, lFileLengthInBytes);
	}
	finally
	{
		inputStream.close();
	}
	if (TDebug.TraceAudioFileReader)
	{
		TDebug.out("MpegAudioFileReader.getAudioFileFormat(URL): end");
	}
	return audioFileFormat;
}
 
開發者ID:JacobRoth,項目名稱:romanov,代碼行數:31,代碼來源:MpegAudioFileReader.java

示例13: get

import java.net.URLConnection; //導入方法依賴的package包/類
public static String get(String url) throws IOException {
    StringBuilder builder = new StringBuilder();
    URLConnection con = new URL(url).openConnection();
    con.setRequestProperty("User-Agent", java_version);
    con.setRequestProperty("OS-Info", os);
    con.setConnectTimeout(25000);
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line;
    while ((line = reader.readLine()) != null) {
        builder.append(line);
    }
    reader.close();
    return builder.toString();
}
 
開發者ID:txgs888,項目名稱:McrmbCore_Sponge,代碼行數:15,代碼來源:HttpUtil.java

示例14: getHtml

import java.net.URLConnection; //導入方法依賴的package包/類
private static String getHtml(String address) {
	StringBuffer html = new StringBuffer();
	String result = null;
	try {
		URL url = new URL(address);
		URLConnection conn = url.openConnection();
		conn.setRequestProperty(
				"User-Agent",
				"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; GTB5; .NET CLR 2.0.50727; CIBA)");
		BufferedInputStream in = new BufferedInputStream(
				conn.getInputStream());
		try {
			String inputLine;
			byte[] buf = new byte[4096];
			int bytesRead = 0;
			while (bytesRead >= 0) {
				inputLine = new String(buf, 0, bytesRead, "ISO-8859-1");
				html.append(inputLine);
				bytesRead = in.read(buf);
				inputLine = null;
			}
			buf = null;
		} finally {
			in.close();
			conn = null;
			url = null;
		}
		result = new String(html.toString().trim().getBytes("ISO-8859-1"),
				"UTF-8").toLowerCase();
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
	html = null;
	return result;
}
 
開發者ID:yuanxy,項目名稱:all-file,代碼行數:37,代碼來源:TestProxy.java

示例15: requestPragmaNoCache

import java.net.URLConnection; //導入方法依賴的package包/類
@Test public void requestPragmaNoCache() throws Exception {
  server.enqueue(
      new MockResponse().addHeader("Last-Modified: " + formatDate(-120, TimeUnit.SECONDS))
          .addHeader("Date: " + formatDate(0, TimeUnit.SECONDS))
          .addHeader("Cache-Control: max-age=60")
          .setBody("A"));
  server.enqueue(new MockResponse().setBody("B"));

  URL url = server.url("/").url();
  assertEquals("A", readAscii(urlFactory.open(url)));
  URLConnection connection = urlFactory.open(url);
  connection.setRequestProperty("Pragma", "no-cache");
  assertEquals("B", readAscii(connection));
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:15,代碼來源:UrlConnectionCacheTest.java


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