开发者

how to connect webserver from android mobile

my application has stored some images i want to sto开发者_运维技巧re that images in the webserver from my android mobile


Use a HttpClient to connect to your webserver from the client. I did it like this to connect to a PHP service:

/**
 * 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;
    }
}

But you should really provide some more information on how you are going to do it, e.g. which technology you use on your webserver


You must send the data as ouput stream in android app and read it in a servlet as input stream from the request object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜