本文整理汇总了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;
}
示例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();
}
示例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;
}
示例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();
}
示例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;
}
}
示例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;
}
示例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();
}
}
示例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);
}
}
示例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()));
}
示例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);
}
}
示例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;
}
示例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;
}
示例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();
}
示例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;
}
示例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));
}