Android网络编程之http发送/请求服务

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ly0904010214/article/details/46352289

最近在学习Android网络编程的知识,以下是今晚学习的一些心得。与大家共同分享。
在实际的应用开发中很多时候需要app向服务器请求数据,那么app如何发送请求呢?下面的代码就是其中的一种情况,使用HttpURLConnection向服务器发送请求的数据,然后处理服务器返回的数据。

下面的代码只是客户端的一个简答测试代码。还需要在pc上安装一个 tomcat服务器 ,然后将demo中的jsp文件部署到tomcat上,具体的方法百度一下便知。



package com.lee.nethttp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    private EditText mEditText = null;
    private Button mButton = null;
    private TextView mTextView = null;
    
    private String mUrl = "http://192.168.0.109:8080/lee/index.jsp";//根据自己主机的ip设置

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mEditText = (EditText) findViewById(R.id.edit);
        mButton = (Button) findViewById(R.id.button);
        mButton.setOnClickListener(mButtonClickListener);
        mTextView = (TextView) findViewById(R.id.text);

    }

    private OnClickListener mButtonClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            String content = mEditText.getText().toString();
            content = toBase64(content);
            String[] params = { content };
            new NetHttpAsyncTask().execute(params);
        }
    };

    private class NetHttpAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            
            try {
                URL url = new URL(mUrl);
                HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                
                connection.setRequestMethod("POST");
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setUseCaches(false);
                connection.setRequestProperty("Content-type",
                        "application/x-www-form-urlencoded;charset=UTF-8");
                connection.setConnectTimeout(3000);
                connection.setReadTimeout(3000);
                
                PrintWriter writer = new PrintWriter(connection.getOutputStream());
                String str = "content" + "=" + params[0];
                writer.print(str);
                writer.flush();
                writer.close();
                
                InputStream input = connection.getInputStream();
                ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();
                int ch;
                while((ch = input.read()) != -1){
                    outputBuffer.write(ch);
                }
                
                result = outputBuffer.toString();
            } catch (IOException e) {
                e.printStackTrace();
            }
            
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            mTextView.setText(result);
        }
    }
    
    private String toBase64(String content){
        try {
            content = Base64.encodeToString(content.getBytes("UTF-8"), Base64.DEFAULT);
            Log.e("lee", "toBase64 content = " + content);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        
        return content;
    }
}




Demo 下载地址



阅读更多
换一批

没有更多推荐了,返回首页