0
点赞
收藏
分享

微信扫一扫

Android(五十三):HttpURLConnection - GET、POST数据请求


展示

Android(五十三):HttpURLConnection - GET、POST数据请求_android

目录

Android(五十三):HttpURLConnection - GET、POST数据请求_c#_02

布局​​PrimaryBlankApp/Resources/layout/activity_main.xml​

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">

<Button
android:id="@+id/btn01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="请求" />

<ImageView
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginBottom="5dp"
android:padding="5dp"
android:background="@color/colorPrimary" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:padding="5dp"
android:background="@color/colorPrimary">

<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</ScrollView>

</LinearLayout>

配置允许Http

  • 报错

​Cleartext HTTP traffic to rap2api.taobao.org not permitted android:usesCleartextTraffic="true"​

  • 解决方法
  • 可参考​​https://developer.android.google.cn/about/versions/pie/android-9.0-changes-28?hl=zh_cn#apache-p​​

<!-- PrimaryBlankApp/Properties/AndroidManifest.xml -->

脚本

​PrimaryBlankApp/MainActivity.cs​

using System;
using System.Collections.Generic;
using System.Text;
using Android.App;
using Android.Graphics;
using Android.OS;
using Android.Widget;
using Java.Lang;
using PrimaryBlankApp.Scripts;
using Thread = Java.Lang.Thread;

namespace PrimaryBlankApp
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : Activity
{
// 请求参数
private readonly List<Dictionary<string, string>> _urls = new List<Dictionary<string, string>>
{
// 图片
new Dictionary<string, string>
{
{ "method", "GET" },
{ "path", "https://img0.baidu.com/it/u=1108406315,1347537283&fm=26&fmt=auto" },
{ "data", "" },
{ "type", "1" }
},
// 图片
new Dictionary<string, string>
{
{ "method", "GET" },
{ "path", "https://img0.baidu.com/it/u=1623519966,546953385&fm=26&fmt=auto" },
{ "data", "" },
{ "type", "1" }
},
// 网站
new Dictionary<string, string>
{
{ "method", "GET" },
{ "path", /" },
{ "data", "" },
{ "type", "2" }
},
// GET 数据
new Dictionary<string, string>
{
{ "method", "GET" },
{ "path", "http://10.10.1.184:8888/getData" },
{ "data", "?name=Lee&sex=男" },
{ "type", "2" }
},
// POST 数据
new Dictionary<string, string>
{
{ "method", "POST" },
{ "path", "http://10.10.1.184:8888/postData" },
{ "data", "zh=中文&en=English" },
{ "type", "2" }
}
};

// 详情数据
private byte[] _bytes;

private Handler _handler;

private Button _btn01;

private ImageView _imageView;

private TextView _textView;

protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);

_imageView = FindViewById<ImageView>(Resource.Id.image_view);
_textView = FindViewById<TextView>(Resource.Id.text_view);
_btn01 = FindViewById<Button>(Resource.Id.btn01);
if (_btn01 != null)
_btn01.Click += delegate
{
_btn01.Text = "请求(Loading ~~~)";
// 耗时操作必须要放在子线程
new Thread(new Runnable(delegate
{
var index = new Random().Next(0, _urls.Count);
var path = _urls[index]["path"];
var method = _urls[index]["method"];
var data = _urls[index]["data"];
var type = _urls[index]["type"];
_bytes = Request.CreateRequest(path, method, data);
var message = new Message();
message.What = Convert.ToInt32(type);
_handler.SendMessage(message);
})).Start();
};

_handler = new Handler(message =>
{
if (_bytes == null)
{
_btn01.Text = "请求(Fail ~~~)";
return;
}
_btn01.Text = "请求(Success ~~~)";

switch (message.What)
{
case 1:
var bitmap = BitmapFactory.DecodeByteArray(_bytes, 0, _bytes.Length);
_imageView.SetImageBitmap(bitmap);
break;
case 2:
var text = Encoding.UTF8.GetString(_bytes);
_textView.Text = text;
break;
}
});
}
}
}

​PrimaryBlankApp/Scripts/Request.cs​

using System.Text;
using Android.Util;
using Java.IO;
using Java.Net;
using Exception = Java.Lang.Exception;

namespace PrimaryBlankApp.Scripts
{
public static class Request
{
private static string TAG = "RequestMessage";

private static HttpURLConnection _conn;

public static byte[] CreateRequest(string path, string method, string data)
{
path += method == "GET" ? data : "";
var url = new URL(path);
_conn = (HttpURLConnection)url.OpenConnection();
if (_conn == null) return null;
_conn.RequestMethod = method;
// 请求超时时间
_conn.ConnectTimeout = 60000;
// 读取超时时间
_conn.ReadTimeout = 60000;

if (method == "POST")
{
_conn.DoInput = true;
_conn.DoOutput = true;
_conn.UseCaches = false;
_conn.OutputStream?.Write(Encoding.UTF8.GetBytes(data)); // 添加参数
}

try
{
if (_conn.ResponseCode == HttpStatus.Ok)
{
Log.Info(TAG, $"{TAG} ---> Success ~~~");
return DataToBytes();
}
}
catch (Exception e)
{
Log.Info(TAG, $"{TAG} ---> Fail ~~~");
e.PrintStackTrace();
}
finally
{
_conn.Disconnect();
}

return null;
}

// 处理数据
private static byte[] DataToBytes()
{
var byteArrayOutputStream = new ByteArrayOutputStream();
var buffer = new byte[1024];
var inputStream = _conn.InputStream;
int len;
while (inputStream != null && (len = inputStream.Read(buffer)) > 0)
{
byteArrayOutputStream.Write(buffer, 0, len);
}

return byteArrayOutputStream.ToByteArray();
}
}
}

举报

相关推荐

0 条评论