此处将为大家介绍关于dart–如何在flutter中使用url编码的主体发出HTTPPOST请求?的详细内容,并且为您解答有关flutterurllauncher的相关问题,此外,我们还将为您介绍关于
此处将为大家介绍关于dart – 如何在flutter中使用url编码的主体发出HTTP POST请求?的详细内容,并且为您解答有关flutter url launcher的相关问题,此外,我们还将为您介绍关于android – 如何在flutter上使用cookie发出http请求?、android – 如何在HTTP post请求的主体中发布params?、dart – Flutter:http post上传图片、dart – 如何在flutter中创建工具栏搜索视图的有用信息。
本文目录一览:- dart – 如何在flutter中使用url编码的主体发出HTTP POST请求?(flutter url launcher)
- android – 如何在flutter上使用cookie发出http请求?
- android – 如何在HTTP post请求的主体中发布params?
- dart – Flutter:http post上传图片
- dart – 如何在flutter中创建工具栏搜索视图
dart – 如何在flutter中使用url编码的主体发出HTTP POST请求?(flutter url launcher)
如果我写body:data我得到错误类型’_InternalLinkedHashMap< String,dynamic>‘不是类型转换中类型’String’的子类型
这是数据对象
var match = { "homeTeam": {"team": "Team A"},"awayTeam": {"team": "Team B"} };
我的要求
var response = await post(Uri.parse(url),headers: { "Accept": "application/json","Content-Type": "application/x-www-form-urlencoded" },body: match,encoding: Encoding.getByName("utf-8"));
解决方法
首先,您需要将json映射转换为String(使用json.encode)
然后,如果要将其作为application / x-www-form-urlencoded发送,则需要对其进行Uri编码.
最后,您需要为要发布名称的参数指定.
例如(注意,这是使用dart:io HttpClient,但它基本相同):
Future<HttpClientResponse> foo() async { Map<String,dynamic> jsonMap = { 'homeTeam': {'team': 'Team A'},'awayTeam': {'team': 'Team B'},}; String jsonString = json.encode(jsonMap); // encode map to json String paramName = 'param'; // give the post param a name String formBody = paramName + '=' + Uri.encodeQueryComponent(jsonString); List<int> bodyBytes = utf8.encode(formBody); // utf8 encode HttpClientRequest request = await _httpClient.post(_host,_port,'/a/b/c'); // it's polite to send the body length to the server request.headers.set('Content-Length',bodyBytes.length.toString()); // todo add other headers here request.add(bodyBytes); return await request.close(); }
以上是针对dart:io版本(当然,你可以在Flutter中使用)
如果您想坚持使用该软件包:http版本,那么您需要稍微调整一下Map. body必须是Map< String,String>.您需要确定您想要的POST参数.你想要两个:homeTeam和awayTeam吗?或者一个,比如,teamJson?
这段代码
Map<String,String> body = { 'name': 'doodle','color': 'blue','homeTeam': json.encode( {'team': 'Team A'},),'awayTeam': json.encode( {'team': 'Team B'},}; Response r = await post( url,body: body,);
在线上产生这个
name=doodle&color=blue&homeTeam=%7B%22team%22%3A%22Team+A%22%7D&awayTeam=%7B%22team%22%3A%22Team+B%22%7D
或者,这个
Map<String,'teamJson': json.encode({ 'homeTeam': {'team': 'Team A'},}),);
在线上产生这个
name=doodle&color=blue&teamJson=%7B%22homeTeam%22%3A%7B%22team%22%3A%22Team+A%22%7D%2C%22awayTeam%22%3A%7B%22team%22%3A%22Team+B%22%7D%7D
包:http客户端负责:编码Uri.encodeQueryComponent,utf8编码(请注意,这是默认值,因此无需指定)并在Content-Length标头中发送长度.您仍然必须执行json编码.
android – 如何在flutter上使用cookie发出http请求?
对于我正在使用的http请求
static Future<Map> postData(Map data) async { http.Response res = await http.post(url,body: data); // post api call Map data = JSON.decode(res.body); return data; }
解决方法
class Session { Map<String,String> headers = {}; Future<Map> get(String url) async { http.Response response = await http.get(url,headers: headers); updateCookie(response); return json.decode(response.body); } Future<Map> post(String url,dynamic data) async { http.Response response = await http.post(url,body: data,headers: headers); updateCookie(response); return json.decode(response.body); } void updateCookie(http.Response response) { String rawCookie = response.headers['set-cookie']; if (rawCookie != null) { int index = rawCookie.indexOf(';'); headers['cookie'] = (index == -1) ? rawCookie : rawCookie.substring(0,index); } } }
android – 如何在HTTP post请求的主体中发布params?
我有一组参数,由用户输入并存储在这里:
RequestParams params = new RequestParams();
params.put("confirmPass", confirmPass);
params.put("username", email);
params.put("password", password);
然后我实例化AsyncHttpClient并实现所需的方法:
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
});
如何发布存储在请求正文中的参数(我使用服务器(mocky.io)来模拟整个过程)?
解决方法:
怎么样:
public static String makePostRequest(String stringUrl, String payload,
Context context) throws IOException {
URL url = new URL(stringUrl);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
String line;
StringBuffer jsonString = new StringBuffer();
uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
uc.setRequestMethod("POST");
uc.setDoInput(true);
uc.setInstanceFollowRedirects(false);
uc.connect();
OutputStreamWriter writer = new OutputStreamWriter(uc.getoutputStream(), "UTF-8");
writer.write(payload);
writer.close();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
while((line = br.readLine()) != null){
jsonString.append(line);
}
br.close();
} catch (Exception ex) {
ex.printstacktrace();
}
uc.disconnect();
return jsonString.toString();
}
其中payload是body JSON字符串.您还需要使用AsyncTask并在doInBackground方法中运行上面的方法,如下所示:
new AsyncTask<String, String, String>() {
@Override
protected String doInBackground(String... params) {
try {
String response = makePostRequest("http://www.example.com",
"{ exampleObject: \"name\" }", getApplicationContext());
return "Success";
} catch (IOException ex) {
ex.printstacktrace();
return "";
}
}
}.execute("");
现在您也可以使用从服务器返回的响应
dart – Flutter:http post上传图片
现在我想用Dart扑灭http请求:
import 'package:http/http.dart' as http; static ocr(File image) async { var url = '${API_URL}ocr'; var bytes = image.readAsBytesSync(); var response = await http.post( url,headers:{ "Content-Type":"multipart/form-data" },body: { "lang":"fas","image":bytes},encoding: Encoding.getByName("utf-8") ); return response.body; }
但是我不知道如何上传图像文件,在上面的代码中我得到异常:错误状态:无法使用内容类型“multipart / form-data”设置Request的正文字段.
我该如何撰写请求正文?
解决方法
但是,可以使用dart:http来执行此操作.而不是使用http.post,您将需要使用http.multipartfile对象.
从dart documentation:
var request = new http.MultipartRequest("POST",url); request.fields['user'] = 'someone@somewhere.com'; request.files.add(http.multipartfile.fromPath( 'package','build/package.tar.gz',contentType: new MediaType('application','x-tar'),)); request.send().then((response) { if (response.statusCode == 200) print("Uploaded!"); });
dart – 如何在flutter中创建工具栏搜索视图
解决方法
class SearchAppBar extends StatefulWidget { @override _SearchAppBarState createState() => new _SearchAppBarState(); } class _SearchAppBarState extends State<SearchAppBar> { Widget appBarTitle = new Text("AppBar Title"); Icon actionIcon = new Icon(Icons.search); @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( centerTitle: true,title:appBarTitle,actions: <Widget>[ new IconButton(icon: actionIcon,onpressed:(){ setState(() { if ( this.actionIcon.icon == Icons.search){ this.actionIcon = new Icon(Icons.close); this.appBarTitle = new TextField( style: new TextStyle( color: Colors.white,),decoration: new Inputdecoration( prefixIcon: new Icon(Icons.search,color: Colors.white),hintText: "Search...",hintStyle: new TextStyle(color: Colors.white) ),);} else { this.actionIcon = new Icon(Icons.search); this.appBarTitle = new Text("AppBar Title"); } }); },] ),); } }
今天关于dart – 如何在flutter中使用url编码的主体发出HTTP POST请求?和flutter url launcher的介绍到此结束,谢谢您的阅读,有关android – 如何在flutter上使用cookie发出http请求?、android – 如何在HTTP post请求的主体中发布params?、dart – Flutter:http post上传图片、dart – 如何在flutter中创建工具栏搜索视图等更多相关知识的信息可以在本站进行查询。
本文标签: