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


Java HttpURLConnection.connect方法代碼示例

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


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

示例1: download

import java.net.HttpURLConnection; //導入方法依賴的package包/類
public static byte[] download(String url) throws IOException {
    InputStream in = null;
    try {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setUseCaches(true);
        conn.connect();
        in = conn.getInputStream();
        return StreamUtils.copyStreamToByteArray(in);
    } catch (IOException ex) {
        throw ex;
    } finally {
        StreamUtils.closeQuietly(in);
    }
}
 
開發者ID:MrStahlfelge,項目名稱:gdx-gamesvcs,代碼行數:17,代碼來源:DownloadUtil.java

示例2: createWithHttp

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * Talks to the http interface to create a file.
 *
 * @param filename The file to create
 * @param perms The permission field, if any (may be null)
 * @throws Exception
 */
private void createWithHttp ( String filename, String perms )
        throws Exception {
  String user = HadoopUsersConfTestHelper.getHadoopUsers()[0];
  // Remove leading / from filename
  if ( filename.charAt(0) == '/' ) {
    filename = filename.substring(1);
  }
  String pathOps;
  if ( perms == null ) {
    pathOps = MessageFormat.format(
            "/webhdfs/v1/{0}?user.name={1}&op=CREATE",
            filename, user);
  } else {
    pathOps = MessageFormat.format(
            "/webhdfs/v1/{0}?user.name={1}&permission={2}&op=CREATE",
            filename, user, perms);
  }
  URL url = new URL(TestJettyHelper.getJettyURL(), pathOps);
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.addRequestProperty("Content-Type", "application/octet-stream");
  conn.setRequestMethod("PUT");
  conn.connect();
  Assert.assertEquals(HttpURLConnection.HTTP_CREATED, conn.getResponseCode());
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:32,代碼來源:TestHttpFSServer.java

示例3: getFileCheckSum

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * <b>GETFILECHECKSUM</b>
 *
 * curl -i "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=GETFILECHECKSUM"
 *
 * @param path
 * @return
 * @throws MalformedURLException
 * @throws IOException
 * @throws AuthenticationException
 */
public String getFileCheckSum(String path) throws MalformedURLException,
        IOException, AuthenticationException {
    String resp = null;
    ensureValidToken();
    String spec = MessageFormat.format(
            "/webhdfs/v1/{0}?op=GETFILECHECKSUM&user.name={1}",
            URLUtil.encodePath(path), this.principal);
    HttpURLConnection conn = authenticatedURL.openConnection(new URL(
            new URL(httpfsUrl), spec), token);

    conn.setRequestMethod("GET");
    conn.connect();
    resp = result(conn, true);
    conn.disconnect();

    return resp;
}
 
開發者ID:Transwarp-DE,項目名稱:Transwarp-Sample-Code,代碼行數:29,代碼來源:PseudoWebHDFSConnection.java

示例4: mkdirs

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * <b>MKDIRS</b>
 *
 * curl -i -X PUT
 * "http://<HOST>:<PORT>/<PATH>?op=MKDIRS[&permission=<OCTAL>]"
 *
 * @param path
 * @return
 * @throws AuthenticationException
 * @throws IOException
 * @throws MalformedURLException
 */
public String mkdirs(String path) throws MalformedURLException,
        IOException, AuthenticationException {
    String resp = null;
    ensureValidToken();
    String spec = MessageFormat.format(
            "/webhdfs/v1/{0}?op=MKDIRS&user.name={1}",
            URLUtil.encodePath(path), this.principal);
    HttpURLConnection conn = authenticatedURL.openConnection(new URL(
            new URL(httpfsUrl), spec), token);
    conn.setRequestMethod("PUT");
    conn.connect();
    resp = result(conn, true);
    conn.disconnect();

    return resp;
}
 
開發者ID:Transwarp-DE,項目名稱:Transwarp-Sample-Code,代碼行數:29,代碼來源:PseudoWebHDFSConnection.java

示例5: getUserInformation

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * 
 * @param accessToken
 * @return JSON with user info
 * @throws IOException
 */
public String getUserInformation(String accessToken) throws IOException {
    String endpoint = AuthProperties.inst().getUserInformationEndpoint();
    
    URL url = new URL(endpoint);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    
    String authorizationHeader = String.format("Bearer %s", accessToken);
    con.addRequestProperty("Authorization", authorizationHeader);
    
    con.setRequestMethod("GET");
    con.connect();
    
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    
    in.close();
    
    return response.toString();
}
 
開發者ID:romulets,項目名稱:wso2is-example,代碼行數:31,代碼來源:UserInformationService.java

示例6: getResourceInputStream

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@Override
protected InputStream getResourceInputStream(final Resource resource, final String entityId) throws IOException {
    final String encodedId = URLEncoder.encode(entityId, "UTF-8");
    final URL url = new URL(resource.getURL().toExternalForm().concat(encodedId));

    final HttpURLConnection httpcon = (HttpURLConnection) (url.openConnection());
    httpcon.setDoOutput(true);
    httpcon.addRequestProperty("Accept", "*/*");
    httpcon.setRequestMethod("GET");
    httpcon.connect();
    return httpcon.getInputStream();
}
 
開發者ID:yuweijun,項目名稱:cas-server-4.2.1,代碼行數:13,代碼來源:DynamicMetadataResolverAdapter.java

示例7: connect

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@Override
public void connect() throws IllegalStateException, IOException {
    if (isConnected()) {
        throw new IllegalStateException("Already connected");
    }

    String url = "http://" + hostname + ":" + port + "/metrics/job/" + URLEncoder.encode(job, "UTF-8");
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("Content-Type", TextFormat.REQUEST_CONTENT_TYPE);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");

    conn.setConnectTimeout(10 * SECONDS_PER_MILLISECOND);
    conn.setReadTimeout(10 * SECONDS_PER_MILLISECOND);
    conn.connect();

    this.connection = conn;
    this.writer = new PrometheusTextWriter(new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8)));
    this.exporter = new DropwizardMetricsExporter(writer);
}
 
開發者ID:dhatim,項目名稱:dropwizard-prometheus,代碼行數:21,代碼來源:Pushgateway.java

示例8: pomFileExists

import java.net.HttpURLConnection; //導入方法依賴的package包/類
private boolean pomFileExists(URL url) {
  try {
    URLConnection urlConnection = url.openConnection();
    if (!(urlConnection instanceof HttpURLConnection)) {
      return false;
    }

    HttpURLConnection connection = (HttpURLConnection) urlConnection;
    connection.setRequestMethod("HEAD");
    connection.setInstanceFollowRedirects(true);
    connection.connect();

    int code = connection.getResponseCode();
    if (code == 200) {
      return true;
    }
  } catch (IOException e) {
    // Something went wrong, fall through.
  }
  return false;
}
 
開發者ID:bazelbuild,項目名稱:migration-tooling,代碼行數:22,代碼來源:DefaultModelResolver.java

示例9: readActivityLog

import java.net.HttpURLConnection; //導入方法依賴的package包/類
private List<ContributionDataEntry> readActivityLog(int page) {
    try {
        HttpURLConnection connect = (HttpURLConnection) new URL(this.getString(R.string.url_events, page, currentSessionData.getLogin())).openConnection();
        connect.setRequestMethod("GET");

        Log.v(TAG, "current session data " + currentSessionData);
        String authentication = "token " + currentSessionData.getToken();
        connect.setRequestProperty("Authorization", authentication);

        connect.connect();
        int responseCode = connect.getResponseCode();

        Log.v(TAG, "responseCode = " + responseCode);
        InputStream inputStream = connect.getInputStream();
        String response = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        Log.v(TAG, "response = " + response);
        JSONArray jsonArray = new JSONArray(response);

        return new ContributionsParser(this).parse(jsonArray);

    } catch (Exception e) {
        Log.e(TAG, "Get contributions failed", e);
        Bundle bundle = new Bundle();
        bundle.putString(TAG, Utils.getStackTrace(e));
        firebaseAnalytics.logEvent(fbAEvent, bundle);
        return null;
    }
}
 
開發者ID:OlgaKuklina,項目名稱:GitJourney,代碼行數:29,代碼來源:UpdaterService.java

示例10: sendJsonPost

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * 向指定 URL 發送Json數據的POST方法的請求
 *
 * @param url   發送請求的 URL
 * @param param 請求參數,請求參數應該是 json的形式。
 * @return 所代表遠程資源的響應結果
 */
public static String sendJsonPost(String url, String param) {
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
        URL realUrl = new URL(url);
        // 打開和URL之間的連接
        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
        // 設置通用的請求屬性
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        // 設置文件類型:
        conn.setRequestProperty("Content-Type", "application/json");
        // 設置文件字符集:
        conn.setRequestProperty("charset", "UTF-8");
        conn.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        conn.setUseCaches(false);
        // 發送POST請求必須設置如下兩行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        conn.connect();
        // 獲取URLConnection對象對應的輸出流
        out = new PrintWriter(conn.getOutputStream());
        // 發送請求參數
        out.print(param);
        // flush輸出流的緩衝
        out.flush();
        out.close();
        // 定義BufferedReader輸入流來讀取URL的響應
        in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        System.out.println("發送 POST 請求出現異常!" + e);
        e.printStackTrace();
    }
    //使用finally塊來關閉輸出流、輸入流
    finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return result;
}
 
開發者ID:cuiods,項目名稱:WIFIProbe,代碼行數:65,代碼來源:HttpRequestUtil.java

示例11: readRaw

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * Reads the raw response from a server.
 * @param connection the HttpURLConnection to read the raw response from.
 * @return The raw response from the server.
 * @throws IOException if an IOException occurs.
 */
public static synchronized String readRaw(HttpURLConnection connection) throws IOException
{
	connection.connect();
	Map<String,List<String>> headMap = connection.getHeaderFields();
	String raw = "";
	//A status line which includes the status code and reason message
	// (e.g., HTTP/1.1 200 OK).
	raw += connection.getHeaderField(null)+'\n';
	//Response header fields
	for(String head : headMap.keySet())
	{
		if(head==null)
			continue;
		raw += head + ": ";
		List<String> vals = headMap.get(head);
		//Response header field values (e.g., Content-Type: text/html).
		for(String v : vals)
			raw += v;
		raw += '\n';
	}
	//An empty line.
	raw += '\n';
	//An optional message body.
	raw += read(connection);
	return raw;
}
 
開發者ID:Jenna3715,項目名稱:ChatBot,代碼行數:33,代碼來源:WebRequest.java

示例12: executePost

import java.net.HttpURLConnection; //導入方法依賴的package包/類
public boolean executePost(String path, Object jsonObject) throws IOException {
    HttpURLConnection conn = getConnection(path, "POST");
    conn.setDoOutput(true);
    conn.connect();
    writeJson(conn, jsonObject);
    boolean b = conn.getResponseCode() == 204;
    conn.getInputStream().close();
    return b;
}
 
開發者ID:stirante,項目名稱:lol-client-java-api,代碼行數:10,代碼來源:ClientApi.java

示例13: getBitmapFromURL

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * Downloading push notification image before displaying it in
 * the notification tray
 */
public Bitmap getBitmapFromURL(String strURL) {
    try {
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
 
開發者ID:StringflowServer,項目名稱:Beach-Android,代碼行數:19,代碼來源:NotificationUtils.java

示例14: createRecord

import java.net.HttpURLConnection; //導入方法依賴的package包/類
/**
 * Creates a dns record
 *
 * @param dnsRecord
 * @return
 */
public PostResponse createRecord(DNSRecord dnsRecord)
{
    try
    {
        HttpURLConnection httpPost = (HttpURLConnection) new URL(PREFIX_URL + "zones/" + cloudFlareConfig.getZoneId() + "/dns_records").openConnection();
        String values = NetworkUtils.GSON.toJson(dnsRecord);

        httpPost.setRequestMethod("POST");
        httpPost.setRequestProperty("X-Auth-Email", cloudFlareConfig.getEmail());
        httpPost.setRequestProperty("X-Auth-Key", cloudFlareConfig.getToken());
        httpPost.setRequestProperty("Content-Length", values.getBytes().length + "");
        httpPost.setRequestProperty("Accept", "application/json");
        httpPost.setRequestProperty("Content-Type", "application/json");
        httpPost.setDoOutput(true);
        httpPost.connect();
        try (DataOutputStream dataOutputStream = new DataOutputStream(httpPost.getOutputStream()))
        {
            dataOutputStream.writeBytes(values);
            dataOutputStream.flush();
        }
        try (InputStream inputStream = httpPost.getInputStream())
        {
            JsonObject jsonObject = toJsonInput(inputStream);
            if (jsonObject.get("success").getAsBoolean())
            {
                System.out.println(prefix + "DNSRecord [" + dnsRecord.getName() + "/" + dnsRecord.getType() + "] was created");
            } else
            {
                throw new CloudFlareDNSRecordException("Failed to create DNSRecord \n " + jsonObject.toString());
            }
            httpPost.disconnect();
            return new PostResponse(dnsRecord, jsonObject.get("result").getAsJsonObject().get("id").getAsString());
        }
    } catch (IOException e)
    {
        e.printStackTrace();
    }
    return null;
}
 
開發者ID:Dytanic,項目名稱:CloudNet,代碼行數:46,代碼來源:CloudFlareService.java

示例15: afterHookedMethod

import java.net.HttpURLConnection; //導入方法依賴的package包/類
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
    try {
        prefs.reload();
        if (prefs.getBoolean(BadIntentConstants.CAPTURE_LOG, false) && AppInformation.Instance.intercept()) {
            String tag = (String) param.args[0];
            String log = (String) param.args[1];
            URL url = ConnectionUtils.getBadIntentURL("/log", prefs, port);
            HttpURLConnection conn = ConnectionUtils.getBadIntentHttpURLConnection(url, prefs);

            conn.setRequestMethod("POST");
            conn.setRequestProperty("__BadIntent__", "Log");
            conn.setRequestProperty("__BadIntent__.package", lpparam.packageName);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);
            conn.connect();

            DataOutputStream writer = new DataOutputStream(conn.getOutputStream());

            Map<String, String> data = new HashMap<>();
            data.put("tag", tag);
            data.put("log", log);
            data.put("logType", logType);
            writer.writeBytes(SerializationUtils.createGson().toJson(data));
            writer.flush();
            writer.close();

            ConnectionUtils.readResponseAndCloseConnection(conn).start();
        }
    } catch (Exception e) {/* best effort */}
}
 
開發者ID:mateuszk87,項目名稱:BadIntent,代碼行數:33,代碼來源:LogHooks.java


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