当前位置: 首页>>代码示例>>Java>>正文


Java HttpURLConnection.setRequestProperty方法代码示例

本文整理汇总了Java中java.net.HttpURLConnection.setRequestProperty方法的典型用法代码示例。如果您正苦于以下问题:Java HttpURLConnection.setRequestProperty方法的具体用法?Java HttpURLConnection.setRequestProperty怎么用?Java HttpURLConnection.setRequestProperty使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.net.HttpURLConnection的用法示例。


在下文中一共展示了HttpURLConnection.setRequestProperty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: get

import java.net.HttpURLConnection; //导入方法依赖的package包/类
public Document get(String url) throws Exception{
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    String user = api.getUser();String password = api.getPassword();
    String authStr = user + ":" + password;
    String authEncoded = Base64.encodeBase64String(authStr.getBytes());
    con.setRequestMethod("GET");
    con.setRequestProperty("Authorization", "Basic " + authEncoded);
    con.setDoOutput(true);
    DocumentBuilderFactory factoryBuilder = DocumentBuilderFactory.newInstance();
    factoryBuilder.setIgnoringComments(true);
    factoryBuilder.setIgnoringElementContentWhitespace(true);
    DocumentBuilder d = factoryBuilder.newDocumentBuilder();
    Document document = d.parse(con.getInputStream());
    return document;
}
 
开发者ID:CodedByYou,项目名称:MAL-,代码行数:17,代码来源:MalGet.java

示例2: rollNewVersionInternal

import java.net.HttpURLConnection; //导入方法依赖的package包/类
private KeyVersion rollNewVersionInternal(String name, byte[] material)
    throws NoSuchAlgorithmException, IOException {
  checkNotEmpty(name, "name");
  Map<String, String> jsonMaterial = new HashMap<String, String>();
  if (material != null) {
    jsonMaterial.put(KMSRESTConstants.MATERIAL_FIELD,
        Base64.encodeBase64String(material));
  }
  URL url = createURL(KMSRESTConstants.KEY_RESOURCE, name, null, null);
  HttpURLConnection conn = createConnection(url, HTTP_POST);
  conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON_MIME);
  Map response = call(conn, jsonMaterial,
      HttpURLConnection.HTTP_OK, Map.class);
  KeyVersion keyVersion = parseJSONKeyVersion(response);
  encKeyVersionQueue.drain(name);
  return keyVersion;
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:18,代码来源:KMSClientProvider.java

示例3: varyMultipleFieldsWithMatch

import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Test public void varyMultipleFieldsWithMatch() throws Exception {
  server.enqueue(new MockResponse()
      .addHeader("Cache-Control: max-age=60")
      .addHeader("Vary: Accept-Language, Accept-Charset")
      .addHeader("Vary: Accept-Encoding")
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setBody("B"));

  URL url = server.url("/").url();
  HttpURLConnection frenchConnection1 = openConnection(url);
  frenchConnection1.setRequestProperty("Accept-Language", "fr-CA");
  frenchConnection1.setRequestProperty("Accept-Charset", "UTF-8");
  frenchConnection1.setRequestProperty("Accept-Encoding", "identity");
  assertEquals("A", readAscii(frenchConnection1));
  HttpURLConnection frenchConnection2 = openConnection(url);
  frenchConnection2.setRequestProperty("Accept-Language", "fr-CA");
  frenchConnection2.setRequestProperty("Accept-Charset", "UTF-8");
  frenchConnection2.setRequestProperty("Accept-Encoding", "identity");
  assertEquals("A", readAscii(frenchConnection2));
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:22,代码来源:ResponseCacheTest.java

示例4: postAndParseJSON

import java.net.HttpURLConnection; //导入方法依赖的package包/类
private JSONObject postAndParseJSON(URL url, String postData) throws IOException {
  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  urlConnection.setDoOutput(true);
  urlConnection.setRequestMethod("POST");
  urlConnection.setRequestProperty(
          "Content-Type", "application/x-www-form-urlencoded");
  urlConnection.setRequestProperty(
          "charset", StandardCharsets.UTF_8.displayName());
  urlConnection.setRequestProperty(
          "Content-Length", Integer.toString(postData.length()));
  urlConnection.setUseCaches(false);
  urlConnection.getOutputStream()
          .write(postData.getBytes(StandardCharsets.UTF_8));
  JSONTokener jsonTokener = new JSONTokener(urlConnection.getInputStream());
  return new JSONObject(jsonTokener);
}
 
开发者ID:googlecodelabs,项目名称:recaptcha-codelab,代码行数:17,代码来源:FeedbackServlet.java

示例5: getConnection

import java.net.HttpURLConnection; //导入方法依赖的package包/类
private static HttpURLConnection getConnection(URL url, String method, String contextType, HttpRequestEntity requestEntity)
        throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(method);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Content-Type", contextType);
    conn.setConnectTimeout(requestEntity.getConnectTimeout());
    conn.setReadTimeout(requestEntity.getReadTimeout());
    if (!requestEntity.getHeaders().isEmpty()) {
        for (Map.Entry<String, String> entry : requestEntity.getHeaders().entrySet()) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    if (requestEntity.getBasicAuth() != null) {
        conn.setRequestProperty("Authorization", requestEntity.getBasicAuth().getEncodeBasicAuth());
    }
    return conn;
}
 
开发者ID:warlock-china,项目名称:azeroth,代码行数:21,代码来源:HttpUtils.java

示例6: createUrlConnection

import java.net.HttpURLConnection; //导入方法依赖的package包/类
private HttpURLConnection createUrlConnection(String urlAsStr, int timeout,
                                              boolean includeSomeGooseOptions) throws IOException {
    URL url = new URL(urlAsStr);
    //using proxy may increase latency
    HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
    hConn.setRequestProperty("User-Agent", userAgent);
    hConn.setRequestProperty("Accept", accept);

    if (includeSomeGooseOptions) {
        hConn.setRequestProperty("Accept-Language", language);
        hConn.setRequestProperty("content-charset", charset);
        hConn.addRequestProperty("Referer", referrer);
        // avoid the cache for testing purposes only?
        hConn.setRequestProperty("Cache-Control", cacheControl);
    }

    // suggest respond to be gzipped or deflated (which is just another compression)
    // http://stackoverflow.com/q/3932117
    hConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
    hConn.setConnectTimeout(timeout);
    hConn.setReadTimeout(timeout);
    return hConn;
}
 
开发者ID:XndroidDev,项目名称:Xndroid,代码行数:24,代码来源:HtmlFetcher.java

示例7: readProxyResponse

import java.net.HttpURLConnection; //导入方法依赖的package包/类
public static Response readProxyResponse(HttpProxyCacheServer proxy, String url, int offset) throws IOException {
    String proxyUrl = proxy.getProxyUrl(url, false);
    if (!proxyUrl.startsWith("http://127.0.0.1")) {
        throw new IllegalStateException("Proxy url " + proxyUrl + " is not proxied! Original url is " + url);
    }
    URL proxiedUrl = new URL(proxyUrl);
    HttpURLConnection connection = (HttpURLConnection) proxiedUrl.openConnection();
    try {
        if (offset >= 0) {
            connection.setRequestProperty("Range", "bytes=" + offset + "-");
        }
        return new Response(connection);
    } finally {
        connection.disconnect();
    }
}
 
开发者ID:Achenglove,项目名称:AndroidVideoCache,代码行数:17,代码来源:ProxyCacheTestUtils.java

示例8: MultipartUtility

import java.net.HttpURLConnection; //导入方法依赖的package包/类
public MultipartUtility(String requestURL, String charset)
        throws IOException {
    this.charset = charset;

    boundary = "===" + System.currentTimeMillis() + "===";

    URL url = new URL(requestURL);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);
    httpConn.setRequestProperty("Content-Type",
            "multipart/form-data; boundary=" + boundary);
    httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
    httpConn.setRequestProperty("Test", "Bonjour");
    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
            true);
}
 
开发者ID:DSM-DMS,项目名称:DMS,代码行数:20,代码来源:MultipartUtility.java

示例9: getData

import java.net.HttpURLConnection; //导入方法依赖的package包/类
public static String getData(URL url) {
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("ERROR");
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

        String output;
        StringBuilder stringBuilder = new StringBuilder();
        while ((output = br.readLine()) != null) {
            stringBuilder.append(output);
        }
        output = stringBuilder.toString();
        conn.disconnect();
        return output;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
开发者ID:ykarim,项目名称:WeatherWatch,代码行数:27,代码来源:NetworkConnect.java

示例10: smallToFull

import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
 * If largest resolution for image at 'thumb' is found, starts downloading
 * and returns null.
 * If it finds a larger resolution on another page, returns the image URL.
 * @param thumb Thumbnail URL
 * @param page Page the thumbnail is retrieved from
 * @return Highest-resolution version of the image based on thumbnail URL and the page.
 */
private String smallToFull(String thumb, String page) {
    try {
        // Fetch the image page
        Response resp = Http.url(page)
                            .referrer(this.url)
                            .cookies(cookies)
                            .response();
        cookies.putAll(resp.cookies());
        Document doc = resp.parse();
        Elements els = doc.select("img.dev-content-full");
        String fsimage = null;
        // Get the largest resolution image on the page
        if (els.size() > 0) {
            // Large image
            fsimage = els.get(0).attr("src");
            logger.info("Found large-scale: " + fsimage);
            if (fsimage.contains("//orig")) {
                return fsimage;
            }
        }
        // Try to find the download button
        els = doc.select("a.dev-page-download");
        if (els.size() > 0) {
            // Full-size image
            String downloadLink = els.get(0).attr("href");
            logger.info("Found download button link: " + downloadLink);
            HttpURLConnection con = (HttpURLConnection) new URL(downloadLink).openConnection();
            con.setRequestProperty("Referer",this.url.toString());
            String cookieString = "";
            for (Map.Entry<String, String> entry : cookies.entrySet()) {
                cookieString = cookieString + entry.getKey() + "=" + entry.getValue() + "; ";
            }
            cookieString = cookieString.substring(0,cookieString.length() - 1);
            con.setRequestProperty("Cookie",cookieString);
            con.setRequestProperty("User-Agent", USER_AGENT);
            con.setInstanceFollowRedirects(true);
            con.connect();
            int code = con.getResponseCode();
            String location = con.getURL().toString();
            con.disconnect();
            if (location.contains("//orig")) {
                fsimage = location;
                logger.info("Found image download: " + location);
            }
        }
        if (fsimage != null) {
            return fsimage;
        }
        throw new IOException("No download page found");
    } catch (IOException ioe) {
        try {
            logger.info("Failed to get full size download image at " + page + " : '" + ioe.getMessage() + "'");
            String lessThanFull = thumbToFull(thumb, false);
            logger.info("Falling back to less-than-full-size image " + lessThanFull);
            return lessThanFull;
        } catch (Exception e) {
            return null;
        }
    }
}
 
开发者ID:RipMeApp,项目名称:ripme,代码行数:69,代码来源:DeviantartRipper.java

示例11: post

import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
 * Sends a POST to the given URL
 */
private static String post(URL url, String content, boolean skipLoggingErrors)
{
    try
    {
        Proxy proxy = MinecraftServer.getServer() == null ? null : MinecraftServer.getServer().getServerProxy();

        if (proxy == null)
        {
            proxy = Proxy.NO_PROXY;
        }

        HttpURLConnection httpurlconnection = (HttpURLConnection)url.openConnection(proxy);
        httpurlconnection.setRequestMethod("POST");
        httpurlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpurlconnection.setRequestProperty("Content-Length", "" + content.getBytes().length);
        httpurlconnection.setRequestProperty("Content-Language", "en-US");
        httpurlconnection.setUseCaches(false);
        httpurlconnection.setDoInput(true);
        httpurlconnection.setDoOutput(true);
        DataOutputStream dataoutputstream = new DataOutputStream(httpurlconnection.getOutputStream());
        dataoutputstream.writeBytes(content);
        dataoutputstream.flush();
        dataoutputstream.close();
        BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(httpurlconnection.getInputStream()));
        StringBuffer stringbuffer = new StringBuffer();
        String s;

        while ((s = bufferedreader.readLine()) != null)
        {
            stringbuffer.append(s);
            stringbuffer.append('\r');
        }

        bufferedreader.close();
        return stringbuffer.toString();
    }
    catch (Exception exception)
    {
        if (!skipLoggingErrors)
        {
            logger.error((String)("Could not post to " + url), (Throwable)exception);
        }

        return "";
    }
}
 
开发者ID:Notoh,项目名称:DecompiledMinecraft,代码行数:50,代码来源:HttpUtil.java

示例12: openConnection

import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Override HttpURLConnection openConnection() throws IOException {
  HttpURLConnection connection = super.openConnection();
  for (Entry<String, String> entry : headers.entrySet()) {
    connection.setRequestProperty(entry.getKey(), entry.getValue());
  }
  return connection;
}
 
开发者ID:apache,项目名称:calcite-avatica,代码行数:8,代码来源:RemoteHttpClientTest.java

示例13: getResponse

import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Override
public ResponseScriptType getResponse(boolean isGET)
{
	try
	{
		final String data = getFormData();

		String extra = "";
		if( isGET && !Check.isEmpty(data) )
		{
			String qs = url.getQuery();
			if( Check.isEmpty(qs) )
			{
				extra += "?" + data;
			}
			else
			{
				extra += "?" + qs + "&" + data;
			}
		}
		final String urlString = url.toString() + extra;

		final URL finalUrl = new URL(urlString);
		final HttpURLConnection conn = (HttpURLConnection) finalUrl.openConnection();

		conn.setRequestMethod(isGET ? "GET" : "POST");
		conn.setAllowUserInteraction(false);
		conn.setInstanceFollowRedirects(true);

		conn.setDoOutput(true);
		conn.setDoInput(true);

		// Send data
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestProperty("Accept", "*/*");

		if( !isGET )
		{
			try( Writer wr = new OutputStreamWriter(conn.getOutputStream()) )
			{
				if( !isGET )
				{
					wr.write(data);
				}
				wr.flush();
			}
		}

		// Get the response
		final String contentType = conn.getContentType();

		try( InputStream is = conn.getInputStream() )
		{
			if( contentType == null || contentType.startsWith("text/") )
			{
				Reader rd = new InputStreamReader(is);
				StringWriter sw = new StringWriter();
				CharStreams.copy(rd, sw);
				return new ResponseScriptTypeImpl(sw.toString(), conn.getResponseCode(), contentType);
			}
			else
			{
				ByteArrayOutputStream os = new ByteArrayOutputStream();
				ByteStreams.copy(is, os);
				return new ResponseScriptTypeImpl(os.toByteArray(), conn.getResponseCode(), contentType);
			}
		}
	}
	catch( IOException e )
	{
		return new ResponseScriptTypeImpl("ERROR: " + e.getMessage(), 400, "text/plain");
	}
}
 
开发者ID:equella,项目名称:Equella,代码行数:74,代码来源:UtilsScriptWrapper.java

示例14: getConnection

import java.net.HttpURLConnection; //导入方法依赖的package包/类
private HttpURLConnection getConnection(String endpoint, String method) throws IOException {
    URL url = new URL("https", "localhost", port, endpoint);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("Authorization", "Basic " + token);
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Accept", "application/json");
    conn.setRequestMethod(method);
    return conn;
}
 
开发者ID:stirante,项目名称:lol-client-java-api,代码行数:10,代码来源:ClientApi.java

示例15: request

import java.net.HttpURLConnection; //导入方法依赖的package包/类
static HttpURLConnection request(URI baseURI, String path, String method)
        throws IOException {
    URL url = baseURI.resolve(path).toURL();
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
    if (method.equals(HttpMethod.POST.name()) || method.equals(HttpMethod.PUT.name())) {
        urlConn.setDoOutput(true);
    }
    urlConn.setRequestMethod(method);
    urlConn.setRequestProperty("Connection", "Keep-Alive");
    return urlConn;
}
 
开发者ID:wso2-extensions,项目名称:siddhi-io-http,代码行数:12,代码来源:HttpServerUtil.java


注:本文中的java.net.HttpURLConnection.setRequestProperty方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。