Accessing a Resource over HTTP-NetworkUtils

介绍了一个用于通过HTTP获取资源的实用工具类NetworkUtils,该类提供了一种简单的方法来获取各种类型的数据资源,如图像、XML文档等,并返回DataInputStream供应用程序进一步处理。

The Hypertext Transport Protocol (HTTP) is a very important application-level network protocol. Most of the access to web resources, including web pages, Extensible Markup Language (XML) documents, images, ringtones, wallpapers, and web services all occur over HTTP.

The Mobile Information Device Profile (MIDP) provides HTTP support via the Generic Connection Framework (GCF) HttpConnection, which provides methods to GET and POST resources over HTTP, read and write HTTP headers, and different methods to read and write the resource, for example, as a stream or a byte array.

In this technical tip, I introduce a helper class, NetworkUtils, that defines a number of HTTP constants and a helper method that uses an HttpConnection to connect to a server over HTTP, get a resource, and return it as a DatanIputStream.

There are other suggested technical tips related to this topic that you may want to read:

The NetworkUtils.java Utility Class

Class NetworkUtils defines various HTTP and MIME-type constants, and the static method getResourcetOverHTTP() to connect to a server over HTTP and retrieve the named resource. The method returns a DataInputStream that can be used to read the content stream in any way you wish.

/*
 * NetworkUtils.java
 *
 * Network Utilities. A simple method to get a resource over 
 * HTTP and return a DataInputStream is provided.
 */

package com.j2medeveloper.com.ttips.utils;

import java.io.IOException;
import java.io.DataInputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

/**
 * Various network utilities. A simple method to get a resource over 
 * HTTP and return a DataInputStream is provided.
 *
 * @author C. Enrique Ortiz
 */
public class NetworkUtils {
   
    /////////////////////////////////////////////////////////////////
    // MIME Types
    /////////////////////////////////////////////////////////////////
    public static final String MIMETYPE_TEXT_PLAIN = "text/plain";
    public static final String MIMETYPE_TEXT_XML = "text/xml";
    public static final String MIMETYPE_APP_XML = "application/xml";
    public static final String MIMETYPE_IMAGE_PNG = "image/png";

    /////////////////////////////////////////////////////////////////
    // HTTP Contants
    /////////////////////////////////////////////////////////////////
    private static final String HTTPHDR_ACCEPT = "Accept";

    private static final String HTTPHDR_USER_AGENT = "User-Agent";
    private static String HTTPHDR_USER_AGENT_VALUE;
    
    private static final String HTTPHDR_CONNECTION = "Connection";
    private static final String HTTPHDR_CONNECTION_CLOSE = "close";
            
    private static final String HTTPHDR_CACHE_CONTROL = "Cache-Control";
    private static final String HTTPHDR_CACHE_CONTROL_NOTRANSFORM = 
            "no-transform";
    private static final String HTTPHDR_CONTENT_LEN = "Content-Length";
    
    static {
        // Retrieve the underlying profile and configuration for User Agent
        String p = System.getProperty("microedition.profiles");
        String c = System.getProperty("microedition.configuration");
        HTTPHDR_USER_AGENT_VALUE = "Profile/" + p + " Configuration/" + c;        
    }
        
    /**
     * Gets a Resource over HTTP, returing an <code>DataInputStream</code> to it
     *
     * @param uri is the URI to use to get the resource to retrieve
     * @pararm mimeType is the (possible) mime type(s) of the resource to retrieve
     *
     * @return an <code>DataInputStream</code> for the input resource
     *
     * @throws <code>IOException</code> is thrown if an error is encountered
     */
    static public DataInputStream getResourceOverHTTP(
            String uri, 
            String mimeType) throws IOException {

        HttpConnection connection = null;
        IOException ioException = null;
        DataInputStream is = null;

        try {
            connection = (HttpConnection) Connector.open(uri, Connector.READ, true);

            connection.setRequestMethod(HttpConnection.GET);

            connection.setRequestProperty(
                    HTTPHDR_ACCEPT, 
                    mimeType);

            connection.setRequestProperty(
                    HTTPHDR_USER_AGENT, 
                    HTTPHDR_USER_AGENT_VALUE);

            connection.setRequestProperty(
                    HTTPHDR_CONNECTION, 
                    HTTPHDR_CONNECTION_CLOSE);

            connection.setRequestProperty(
                    HTTPHDR_CACHE_CONTROL, 
                    HTTPHDR_CACHE_CONTROL_NOTRANSFORM);

            connection.setRequestProperty(
                    HTTPHDR_CONTENT_LEN, 
                    String.valueOf("0"));

            //////////////////////////////////////
            // Send GET, receive initial response
            //////////////////////////////////////
            int rc = connection.getResponseCode();

            /////////////////////////////////////////////////////////
            // If an HTTP error was encountered, stop, indicate error
            /////////////////////////////////////////////////////////
            if (rc != HttpConnection.HTTP_OK) {
                // Log error, throw IO exception
                ioException = new IOException("Http Error, response Code is " + rc);
                throw ioException;
            }
            is = connection.openDataInputStream();
        } catch (IOException ioe) {
            // Log error, throw IO exception
            throw ioe; // Propagate the IO Exception
        } finally {
            if (connection != null) connection.close();
            return is;
        }
    }
}
 

The method opens an HTTP connection to the specified Uniform Resource Identifier (URI), sets the HTTP request headers to indicate the accepted MIME types, the user-agent, the connection persistence to not persist, and the cache control option to tell proxies not to transform or compress the content. The GET request is sent to the server by calling method getResponseCode(). If no error is encountered, a DataInputStream is returned, and passed back to the caller, otherwise and IOException is thrown.

Using NetworkUtils.java

To use this utility class and its static method getResourceOverHTTP(), all you have to do is provide the URI to the resource on the web, and its MIME type. If successful, the method will return a DataInputStream to the resource, or throw an IOException that must be handled. Remember that all network operations should be dispatched in a separate thread of execution to avoid blocking other threads, and to close streams when done using them:

public final class MyClass implements Runnable {
:
    private String thPngUri; // URI used by thread
    :


    /**
     * Dispatches the thread to retrieve the resource over HTTP
     * 
     * @param uri the URI to the resource
     */
    private void dispatchGetResourceTh(String uri) {
        thPngUri = uri; // set class-wide member, that is used by thread
        Thread th = new Thread(this);
        th.start();
    }

    :

    /**
     * Thread of execution
     */
    public void run() {
        DataInputStream is = null;
        try {
            is = NetworkUtils.getResourceOverHTTP(
                    thPngUri, NetworkUtils.MIMETYPE_IMAGE_PNG);
        } catch (IOException ioe) {
            // Log error, exit
                return;
        }
        notifyRetrievalComplete(thUri, is);
    }
}
 

Once method getResourceOverHTTP() returns successfully with the DataInputStream to the resource, the method notifyRetrievalComplete() is called to further process the resource, for example, if the resource is an image, to create an Image from the DataInputStream:

private void notifyRetrievalComplete (
            String resourceName, DataInputStream is) {
    :

    // Create an Image from the DataInputStream.
    Image image = Image.createImage(is);
    :

    // Close the stream when done
    is.close();
    :
}
 

... or if the resource is a MIDI audio resource, to create a media Player from the DataInputStream:

private static String mimeType = "audio/midi";
:

private void notifyRetrievalComplete (
            String resourceName, DataInputStream is) {

    // Create a Player to play back media from the DataInputStream.
    Player myPlayer = Manager.createPlayer(is, mimeType)
    :

    // Close the stream when done
    is.close();
    :
}
 
Conclusion

This technical tip introduced a simple method that MIDlets can use to retrieve a resource over HTTP in the form of a DataInputStream. The DataInputStream could represent various data types such as an image, XML document, or a video stream that can read the application and process it accordingly. You can extend this class with more MIME types, and with other helper methods, for example, a method to retrieve the resource as a byte array, or a more sophisticated send/receive method.

Acknowledgement

I would like to thank Roger Riggs for his technical review and feedback on this article.

 
<think>好的,我现在需要处理用户关于“Error while accessing target resource solution”的问题。首先,用户之前提到在安装GI时,第二个节点的root.sh遇到了错误,具体是启动ASM和Oracle Clusterware堆栈失败。我需要根据用户提供的引用信息和常见解决方案来给出建议。 首先,我应该回顾用户提供的引用内容。引用[1]提到了启动ASM失败的情况,引用[2]则讨论了容错和恢复机制,比如数据持久化存储和恢复策略。这可能与资源访问错误有关联,比如节点间通信问题或资源冲突。 接下来,我需要考虑常见的导致资源访问错误的原因。比如权限问题、资源冲突、网络连接问题、配置错误、依赖服务未启动、存储路径问题等。这些都可能引发用户提到的错误。 然后,我需要一步步给出解决方案。首先检查权限,确保用户和组正确,权限设置合理。然后检查资源冲突,使用crsctl检查资源状态,停止冲突的资源。接下来是网络检查,确认节点间通信正常,hosts文件配置正确。检查配置文件,如OCR和Voting Disk的路径是否正确。查看日志文件,如crsd.log和ohasd.log,寻找具体错误信息。此外,可能需要重启集群服务或应用补丁。 同时,结合引用[2]中的容错机制,建议用户确保数据持久化和中间结果的恢复策略,比如检查ASM实例的日志和存储配置,确保存储设备可用。可能需要重新挂载存储或检查ASM磁盘组的状态。 最后,生成相关问题,帮助用户进一步排查问题,比如权限问题、资源冲突处理、网络诊断工具、ASM配置检查、集群日志位置等。这些问题能引导用户深入检查各个可能出错的环节。</think>### 访问目标资源时出现错误的解决方案 #### 1. 错误背景分析 当出现类似“Error while accessing target resource”的错误时,通常与以下原因相关: - **权限不足**:用户或进程无法访问目标资源(如文件、存储设备或网络端口)[^1]。 - **资源冲突**:目标资源已被其他进程占用(例如端口被占用、存储路径重复挂载)[^1]。 - **网络/存储配置问题**:节点间通信异常或存储路径不可达[^1][^2]。 - **依赖服务未启动**:如ASM实例未正确初始化或集群服务未完全启动[^1]。 --- #### 2. 逐步解决方案 ##### (1) 检查权限与用户组 - **确认资源所有者**:例如ASM磁盘的权限需属于`grid:oinstall`: ```bash ls -l /dev/oracleasm/disks/ ``` 若权限错误,使用以下命令修正: ```bash chown grid:oinstall /dev/oracleasm/disks/* ``` ##### (2) 排查资源冲突 - **检查资源状态**: ```bash crsctl stat res -t ``` 若发现资源状态为`FAILED`,尝试停止冲突资源: ```bash crsctl stop res ora.asm -init ``` ##### (3) 验证网络与存储配置 - **检查节点间通信**: ```bash ping <节点IP> cluvfy comp nodecon -n <节点名> ``` - **确认存储路径有效性**: ```bash ls -l /dev/oracleasm/disks/ asmcmd lsdsk ``` ##### (4) 查看日志定位具体错误 - **关键日志路径**: - ASM日志:`$ORACLE_BASE/diag/asm/+asm/+ASM{instance_number}/trace/alert_+ASM{instance_number}.log` - 集群日志:`$GRID_HOME/log/<节点名>/crsd/crsd.log` --- #### 3. 容错与恢复机制 根据引用[2],若错误与中间结果丢失或硬件故障相关: - **持久化存储检查**:确保ASM磁盘组已正确挂载且状态为`MOUNTED`。 - **数据恢复策略**: ```sql -- 在ASM实例中检查磁盘组状态 SELECT name, state FROM v$asm_diskgroup; -- 若状态异常,尝试重新挂载 ALTER DISKGROUP <磁盘组名> MOUNT; ``` --- #### 4. 高级修复方法 若上述步骤无效: - **重启集群服务**: ```bash crsctl stop has crsctl start has ``` - **应用补丁**:某些情况下需应用Oracle Grid Infrastructure的补丁(参考MOS文档)。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值