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