如何从Android手机连接webserver

时间:2010-12-09 09:33:49

标签: android webserver

我的应用程序存储了一些我希望将这些图像存储在我的Android手机中的网络服务器中的图像

2 个答案:

答案 0 :(得分:0)

使用HttpClient从客户端连接到您的网络服务器。我这样做是为了连接到PHP服务:

/**
 * Transmits a file from the local filesystem to a web-server
 * @param fileName the local file to transmit
 * @param params the remote parameters for the php script
 * @return the server response as a String
 */
public String httpUploadFile(String fileName, String params) {
    if(fileName==null) {
        return "ERROR file is null";
    } else {
        DDLog.i(TAG, "Initiating httpUpload for file "+fileName);
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(300000)); // 300 seconds -> 5 min
        httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        String url = this.baseURL + "?" + params;
        HttpPost httpPost = new HttpPost(url);

        MultipartEntity mpEntity = new MultipartEntity();
        File file = new File(fileName);
        double fileBytes = file.length();
        DecimalFormat decimalFormat = new DecimalFormat("0.000");
        Log.i(TAG, "httpUpload file: "+fileName+" with "+file.length()+" bytes; "+decimalFormat.format(fileBytes/1024)+" kb; "+decimalFormat.format(fileBytes/1048576)+" mb");

        FileBody bodyFile = new FileBody(file);
        mpEntity.addPart("pic", bodyFile);

        httpPost.setEntity(mpEntity);

        HttpResponse httpResponse = null;
        HttpEntity responseEntity = null;
        String response = "";
        try {
            httpResponse = httpClient.execute(httpPost);
            responseEntity = httpResponse.getEntity();
            response = EntityUtils.toString(responseEntity);

        } catch (SocketException e) {
            e.printStackTrace();
            DDLog.e(TAG, e.getMessage(), e);
            response = "SOCKET EXCEPTION " + e.getMessage();

        } catch (SocketTimeoutException e) {
            e.printStackTrace();
            DDLog.e(TAG, e.getMessage(), e);
            response = "SOCKET TIMEOUT";

        } catch (ClientProtocolException e) {
            e.printStackTrace();
            DDLog.e(TAG, e.getMessage(), e);
        } catch (IOException e) {
            e.printStackTrace();
            DDLog.e(TAG, e.getMessage(), e);
        }

        DDLog.i(TAG, "HttpResponse: "+response);

        return response;
    }
}

但是你应该提供一些关于你将如何做的更多信息,例如:您在网络服务器上使用的技术

答案 1 :(得分:0)

您必须在android app中将数据作为输出流发送,并在servlet中将其作为来自请求对象的输入流读取。