Android 网络编程

37 篇文章 0 订阅
public class Main extends Activity implements OnClickListener
{
    private EditText etBookName; 
    @Override
    public void onClick(View view)
    {
        // 读者需要将本例中的IP换成自己机器的IP
        String url = "http://192.168.17.105:8080/querybooks/QueryServlet";
        TextView tvQueryResult = (TextView) findViewById(R.id.tvQueryResult);


        HttpResponse httpResponse = null;
        try
        {
            switch (view.getId())
            {
            // 提交HTTP GET请求
                case R.id.btnGetQuery:
                    // 向url添加请求参数
                    url += "?bookname=" + etBookName.getText().toString();
                    // 第1步:创建HttpGet对象
                    HttpGet httpGet = new HttpGet(url);
                    // 第2步:使用execute方法发送HTTP GET请求,并返回HttpResponse对象
                    httpResponse = new DefaultHttpClient().execute(httpGet);
                    // 判断请求响应状态码,状态码为200表示服务端成功响应了客户端的请求
                    if (httpResponse.getStatusLine().getStatusCode() == 200)
                    {
                        // 第3步:使用getEntity方法获得返回结果
                        String result = EntityUtils.toString(httpResponse
                                .getEntity());
                        // 去掉返回结果中的“\r”字符,否则会在结果字符串后面显示一个小方格
                        tvQueryResult.setText(result.replaceAll("\r", ""));
                    }
                    break;
                // 提交HTTP POST请求
                case R.id.btnPostQuery:
                    // 第1步:创建HttpPost对象
                    HttpPost httpPost = new HttpPost(url);
                    // 设置HTTP POST请求参数必须用NameValuePair对象
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("bookname", etBookName
                            .getText().toString()));
                    // 设置HTTP POST请求参数
                    httpPost.setEntity(new UrlEncodedFormEntity(params,
                            HTTP.UTF_8));
                    // 第2步:使用execute方法发送HTTP POST请求,并返回HttpResponse对象
                    httpResponse = new DefaultHttpClient().execute(httpPost);
                    if (httpResponse.getStatusLine().getStatusCode() == 200)
                    {
                        // 第3步:使用getEntity方法获得返回结果
                        String result = EntityUtils.toString(httpResponse
                                .getEntity());
                        // 去掉返回结果中的“\r”字符,否则会在结果字符串后面显示一个小方格
                        tvQueryResult.setText(result.replaceAll("\r", ""));
                    }
                    break;
            }
        }
        catch (Exception e)
        {
            tvQueryResult.setText(e.getMessage());
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btnGetQuery = (Button) findViewById(R.id.btnGetQuery);
        Button btnPostQuery = (Button) findViewById(R.id.btnPostQuery);
        etBookName = (EditText) findViewById(R.id.etBookName);
        etBookName.setText("开发");
        btnGetQuery.setOnClickListener(this);
        btnPostQuery.setOnClickListener(this);

    }

另外一种方式,HttpURLConnection

public class Main extends Activity implements OnFileBrowserListener
{

    @Override
    public void onDirItemClick(String path)
    {

    }  

    @Override
    public void onFileItemClick(String filename)
    {
        String uploadUrl = "http://192.168.17.105:8080/upload/UploadServlet";
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "******";
        try
        {
            URL url = new URL(uploadUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url
                    .openConnection();
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);

            DataOutputStream dos = new DataOutputStream(
                    httpURLConnection.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + end);
            dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
                    + filename.substring(filename.lastIndexOf("/") + 1)
                    + "\""
                    + end);
            dos.writeBytes(end);

            FileInputStream fis = new FileInputStream(filename);
            byte[] buffer = new byte[8192]; // 8k
            int count = 0;
            while ((count = fis.read(buffer)) != -1)
            {
                dos.write(buffer, 0, count);

            }
            fis.close();

            dos.writeBytes(end);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
            dos.flush();

            InputStream is = httpURLConnection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String result = br.readLine();

            Toast.makeText(this, result, Toast.LENGTH_LONG).show();
            dos.close();
            is.close();

        }
        catch (Exception e)
        {
            setTitle(e.getMessage());
        }

    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        FileBrowser fileBrowser = (FileBrowser) findViewById(R.id.filebrowser);
        fileBrowser.setOnFileBrowserListener(this);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值