How to get file via HttpGet from pc in local netwo

2019-06-13 01:25发布

i have c# program running on my pc listenning http requests and i try to make an application which gets a file from my pc via HttpGet.

new HttpGet(url + filepath);

the file is in the same directory and the path is C://Users/abc/def/test.txt

but if i write this to filepath i can not get the file. what should i write to filepath?

Thanks in advance

标签: android http url
1条回答
家丑人穷心不美
2楼-- · 2019-06-13 01:31

You need to create an AsyncTask to do your request 'cause since Android Honeycomb, you cannot add a network request on the main thread.

Here is an example :

private class HttpGetter extends AsyncTask<URL, Void, Void> {

                @Override
                protected Void doInBackground(URL... urls) {
                        // TODO Auto-generated method stub
                        StringBuilder builder = new StringBuilder();
                        HttpClient client = new DefaultHttpClient();
                        HttpGet httpGet = new HttpGet(urls[0]);

                        try {
                                HttpResponse response = client.execute(httpGet);
                                StatusLine statusLine = response.getStatusLine();
                                int statusCode = statusLine.getStatusCode();
                                if (statusCode == 200) {
                                        HttpEntity entity = response.getEntity();
                                        InputStream content = entity.getContent();
                                        BufferedReader reader = new BufferedReader(
                                                        new InputStreamReader(content));
                                        String line;
                                        while ((line = reader.readLine()) != null) {
                                                builder.append(line);
                                        }
                                        Log.v("Getter", "Your data: " + builder.toString()); //response data
                                } else {
                                        Log.e("Getter", "Failed to download file");
                                }
                        } catch (ClientProtocolException e) {
                                e.printStackTrace();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }

                        return null;
                }
    }

HttpGetter get = new HttpGetter();
get.execute("http://192.168.1.2/song.mp3");
查看更多
登录 后发表回答