Andrid网络操作之POST与GET的网络请求

一:从服务器中获取数据
在这里插入图片描述
二:GET与POST的区别
在这里插入图片描述

在这里插入图片描述
三:代码演示Get请求
先创建出一个展示界面为在这里插入图片描述
实现网络的时间必须要在Manifast中先声明

<uses-permission android:name="android.permission.INTERNET"/>

基础版的实现界面的代码为

public class NetworkActivity extends AppCompatActivity implements 	View.OnClickListener {

private TextView mTextView;
private Button mButton;
private static final String TAG = "NetworkActivity";
private String mResult;
private Button mParseDataButton;

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

    findViews();
    setListeners();

}

private void findViews() {
    mTextView = findViewById(R.id.textView);
    mButton = findViewById(R.id.getButton);
    mParseDataButton = findViewById(R.id.parseDataButton);
}

private void setListeners() {
    mButton.setOnClickListener(this);
    mParseDataButton.setOnClickListener(this);
}
//做网络请求的时间,要利用多线程,不然会报错
 public void onClick(View v) {
    switch (v.getId()) {
        case R.id.getButton:
         new Thread(new Runnable() {
                public void run() {
                	try{
                		URL url = new URL ("http://www.imooc.com/api/teacher?	type=2&page=1";)
                   		HttpUrlConnection connection = (HttpUrlConnection)	url.openConnection();
                   		connection.setConnectTimeout(30000);
        				connection.setRequestMethod("GET");  // GET POST
        				connection.setRequestProperty("Content-Type", "application/json");
        				connection.setRequestProperty("Charset", "UTF-8");
        				connection.setRequestProperty("Accept-Charset", "UTF-8");
        				connection.connect();      //发起连接    
        				int responseCode = connection.getResponseCode();    
        				String responseMessage = connection.getResponseMessage();    
   if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = connection.getInputStream();
            mResult = streamToString(inputStream);
					
			runOnUiThread(new Runnable() {
				public void run(){
				 	mResult = decode(mResult);
					mTextView.setText(mResult);
					}
				});


	} else {
			Log.e(TAG, "run : error code "+responseCode + "message " + responseMessage);
					
  } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}                    			

*1.注意做网络请求的时间必须要建立多线程来进行操作
2.更新ui要使用runOnUiThread的方法

工具代码:1.将Unicode字符转换为UTF-8类型字符串

  /**
 * 将Unicode字符转换为UTF-8类型字符串
 */
public static String decode(String unicodeStr) {
    if (unicodeStr == null) {
        return null;
    }
    StringBuilder retBuf = new StringBuilder();
    int maxLoop = unicodeStr.length();
    for (int i = 0; i < maxLoop; i++) {
        if (unicodeStr.charAt(i) == '\\') {
            if ((i < maxLoop - 5)
                    && ((unicodeStr.charAt(i + 1) == 'u') || (unicodeStr
                    .charAt(i + 1) == 'U')))
                try {
                    retBuf.append((char) Integer.parseInt(unicodeStr.substring(i + 2, i + 6), 16));
                    i += 5;
                } catch (NumberFormatException localNumberFormatException) {
                    retBuf.append(unicodeStr.charAt(i));
                }
            else {
                retBuf.append(unicodeStr.charAt(i));
            }
        } else {
            retBuf.append(unicodeStr.charAt(i));
        }
    }
    return retBuf.toString();
}

2.将输入流转换成字符串

   /**
 * 将输入流转换成字符串
 *
 * @param is 从网络获取的输入流
 * @return 字符串
 */
public String streamToString(InputStream is) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        baos.close();
        is.close();
        byte[] byteArray = baos.toByteArray();
        return new String(byteArray);
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        return null;
    }
}

四.POST请求
步骤与Get的步骤相同,参数的处理不同
与GET不同的地方为

在这里插入图片描述

这里的getEncodeValue是防止输入的不是UTF-8的格式,在此次进行修改在这里插入图片描述

五.使用场景
Post使用于首页界面
GET使用与密码登录界面

猜你喜欢

转载自blog.csdn.net/Derrick_itRose/article/details/108415000