本文整理汇总了Java中java.net.HttpURLConnection.getInputStream方法的典型用法代码示例。如果您正苦于以下问题:Java HttpURLConnection.getInputStream方法的具体用法?Java HttpURLConnection.getInputStream怎么用?Java HttpURLConnection.getInputStream使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.HttpURLConnection
的用法示例。
在下文中一共展示了HttpURLConnection.getInputStream方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: run
import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Override
public void run() {
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream stream = connection.getInputStream();
int responseCode = connection.getResponseCode();
ByteArrayOutputStream responseBody = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
int bytesRead = 0;
while ((bytesRead = stream.read(buffer)) > 0) {
responseBody.write(buffer, 0, bytesRead);
}
listener.onReceivedBody(responseCode, responseBody.toByteArray());
}
catch (Exception e) {
listener.onError(e);
}
}
示例2: getStringFromWebsite
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public static String getStringFromWebsite(URL url) throws MalformedURLException, IOException{
StringBuilder stringBuilder = new StringBuilder();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36");
conn.setRequestProperty("X-HTTP-Method-Override", "GET");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8")));
String inputLine;
while ((inputLine = in.readLine()) != null) {
stringBuilder.append(inputLine);
}
in.close();
return stringBuilder.toString();
}
示例3: checkLatestVersion
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private String checkLatestVersion() {
String result = REALM_VERSION;
try {
URL url = new URL(VERSION_URL + REALM_VERSION);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(READ_TIMEOUT);
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String latestVersion = rd.readLine();
// if the obtained string does not match the pattern, we are in a separate network.
if (latestVersion.matches(REALM_VERSION_PATTERN)) {
result = latestVersion;
}
rd.close();
} catch (IOException e) {
// We ignore this exception on purpose not to break the build system if this class fails
}
return result;
}
示例4: getResponseFromHttpUrl
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* This method returns the entire result from the HTTP response.
*
* @param url The URL to fetch the HTTP response from.
* @return The contents of the HTTP response.
* @throws IOException Related to network and stream reading
*/
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
示例5: performHandshake
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Internally performs the handshake operation by calling the given <code>url</code> and examining the response.
*
* @param url The URL to call
* @return the status of the operation
* @throws IOException on I/O errors
*/
private ResponseStatus performHandshake(String url) throws IOException {
HttpURLConnection connection = Caller.getInstance().openConnection(url);
InputStream is = connection.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
String status = r.readLine();
int statusCode = ResponseStatus.codeForStatus(status);
ResponseStatus responseStatus;
if (statusCode == ResponseStatus.OK) {
this.sessionId = r.readLine();
this.nowPlayingUrl = r.readLine();
this.submissionUrl = r.readLine();
responseStatus = new ResponseStatus(statusCode);
} else if (statusCode == ResponseStatus.FAILED) {
responseStatus = new ResponseStatus(statusCode, status.substring(status.indexOf(' ') + 1));
} else {
return new ResponseStatus(statusCode);
}
r.close();
return responseStatus;
}
示例6: getBitmapFromURL
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (IOException e) {
// Log exception
return null;
}
}
示例7: testWriteMoreThanContentLengthWriteOneByte
import java.net.HttpURLConnection; //导入方法依赖的package包/类
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testWriteMoreThanContentLengthWriteOneByte()
throws Exception {
URL url = new URL(NativeTestServer.getEchoBodyURL());
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
// Set a content length that's 1 byte short.
connection.setFixedLengthStreamingMode(TestUtil.UPLOAD_DATA.length - 1);
OutputStream out = connection.getOutputStream();
for (int i = 0; i < TestUtil.UPLOAD_DATA.length - 1; i++) {
out.write(TestUtil.UPLOAD_DATA[i]);
}
try {
// Try upload an extra byte.
out.write(TestUtil.UPLOAD_DATA[TestUtil.UPLOAD_DATA.length - 1]);
// On Lollipop, default implementation only triggers the error when reading response.
connection.getInputStream();
fail();
} catch (ProtocolException e) {
// Expected.
String expectedVariant = "expected 0 bytes but received 1";
String expectedVariantOnLollipop = "expected " + (TestUtil.UPLOAD_DATA.length - 1)
+ " bytes but received " + TestUtil.UPLOAD_DATA.length;
assertTrue(expectedVariant.equals(e.getMessage())
|| expectedVariantOnLollipop.equals(e.getMessage()));
}
connection.disconnect();
}
示例8: testWithPort
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private void testWithPort(int port) throws Exception {
MonitorService srv = new HTTPMetricsServer();
Context context = new Context();
if (port > 1024) {
context.put(HTTPMetricsServer.CONFIG_PORT, String.valueOf(port));
} else {
port = HTTPMetricsServer.DEFAULT_PORT;
}
srv.configure(context);
srv.start();
Thread.sleep(1000);
URL url = new URL("http://0.0.0.0:" + String.valueOf(port) + "/metrics");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
String result = "";
while ((line = reader.readLine()) != null) {
result += line;
}
reader.close();
Map<String, Map<String, String>> mbeans = gson.fromJson(result, mapType);
Assert.assertNotNull(mbeans);
Map<String, String> memBean = mbeans.get("CHANNEL.memChannel");
Assert.assertNotNull(memBean);
JMXTestUtils.checkChannelCounterParams(memBean);
Map<String, String> pmemBean = mbeans.get("CHANNEL.pmemChannel");
Assert.assertNotNull(pmemBean);
JMXTestUtils.checkChannelCounterParams(pmemBean);
srv.stop();
System.out.println(String.valueOf(port) + "test success!");
}
示例9: getResponseStringFromConn
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private static String getResponseStringFromConn(HttpURLConnection conn) throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
final StringBuilder stringBuffer = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
return stringBuffer.toString();
}
}
示例10: get
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* 鍙戦�丟et璇锋眰
* @param url
* @return
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws KeyManagementException
*/
public static String get(String url) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
if(enableSSL){
return get(url,true);
}else{
StringBuffer bufferRes = null;
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
// 杩炴帴瓒呮椂
http.setConnectTimeout(25000);
// 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
http.setReadTimeout(25000);
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 鍏抽棴杩炴帴
http.disconnect();
}
return bufferRes.toString();
}
}
示例11: testBug49424NoChunking
import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Test
public void testBug49424NoChunking() throws Exception {
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context root = tomcat.addContext("", null);
Tomcat.addServlet(root, "Bug37794", new Bug37794Servlet());
root.addServletMapping("/", "Bug37794");
tomcat.start();
HttpURLConnection conn = getConnection("http://localhost:" + getPort() + "/");
InputStream is = conn.getInputStream();
assertNotNull(is);
}
示例12: getInputStream
import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Override
protected InputStream getInputStream(HttpURLConnection conn) throws Exception {
// Get the input stream from the connection. Actually returns the underlying stream or IcyInputStream
String smetaint = conn.getHeaderField( "icy-metaint");
InputStream ret = conn.getInputStream();
if (!metadataEnabled) {
LogHelper.v(LOG_TAG, "Metadata not enabled");
}
else if (smetaint != null) {
int period = -1;
try {
period = Integer.parseInt( smetaint);
}
catch (Exception e) {
LogHelper.e(LOG_TAG, "The icy-metaint '" + smetaint + "' cannot be parsed: '" + e);
}
if (period > 0) {
LogHelper.v(LOG_TAG, "The dynamic metainfo is sent every " + period + " bytes");
ret = new IcyInputStream(ret, period, playerCallback, null);
}
}
else LogHelper.v(LOG_TAG, "This stream does not provide dynamic metainfo");
return ret;
}
示例13: callUrlAndParseResult
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public String callUrlAndParseResult(String langFrom, String langTo,
String word) throws Exception
{
String url = "https://translate.googleapis.com/translate_a/single?"+
"client=gtx&"+
"sl=" + langFrom +
"&tl=" + langTo +
"&dt=t&q=" + URLEncoder.encode(word, "UTF-8");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String result = parseResult(response.toString());
if(result.equals("")){
return word;
} else {
return result;}
}
示例14: uploadEditorContent
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public static String[] uploadEditorContent(TestSceneController controller) throws Exception
{
String url = "http://danieloluwadare.com/write.php";
url = "http://ec2-52-14-237-83.us-east-2.compute.amazonaws.com/write.php";
//local
url = "http://localhost/danielOluwadare.com/write.php";
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
/*********************/
/*
school = "neiu";
dept = "304-17";
semester = "spr2017";
test = "midterm";
studentId = "265456";
*/
String content = controller.getCode();
String newContent = "";
for( int i=0; i<content.length(); i++ )
{
if( content.charAt(i) == '+' )
newContent += "%2B";
else if( content.charAt(i) == '\t')
newContent += " ";
else
newContent += content.charAt(i);
}
String urlParameters = "classID=" + controller.getCourse() + "&semester=" + controller.getSemester() +
"&testDesc=" + controller.getTest() + "&studentID=" + controller.getStudentId() +
"&school=" + controller.getSchool() + "&fileName=" + controller.getProblemName() +
"&content=" + newContent;
byte[] postData = urlParameters.getBytes( java.nio.charset.StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String request = url;
URL url2 = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url2.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
wr.write( postData );
}
StringBuilder sb = new StringBuilder();
int HttpResult = conn.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null)
{
sb.append(line);
}
br.close();
String res = sb.toString();
System.out.println(res);
res = res.replaceAll("\\[", "").replaceAll("\\]","");
String[] retList = res.split(",", -1);
return retList;
}
else
{
System.out.println(conn.getResponseMessage());
return new String[0];
}
}
示例15: getImageStream
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private InputStream getImageStream(String filePath) throws Exception{
URL url = new URL(filePath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
return conn.getInputStream();
}
return null;
}