Android开发-网路编程之post提交文本内容
拉大锯
发表于
2019-12-10 02:17
4519
android
卓开发
网络编程
基础课程
安卓开发
前面我们学习了使用get去请求了文本内容,我们获取到了json数据,并且解析,显示到UI上。
接下来我们看看如何去提交文本。
本文为网络编程系列文章,关于权限和网络配置看前面的文章。
接口地址
/post/comment
提交内容:
{
"articleId":"234123",
"commentContent":"这是评论内容"
}
请求代码
public void postRequest(View view) {
new Thread(new Runnable() {
@Override
public void run() {
OutputStream outputStream = null;
InputStream inputStream = null;
try {
URL url = new URL(BASE_URL + "/post/comment");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setRequestProperty("Content-Type","application/json;charset=UTF-8");
httpURLConnection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9");
httpURLConnection.setRequestProperty("Accept","application/json, text/plain, */*");
CommentItem commentItem = new CommentItem("234134123","你的文章写得也太好了!");
Gson gson = new Gson();
String jsonStr = gson.toJson(commentItem);
byte[] bytes = jsonStr.getBytes("UTF-8");
Log.d(TAG,"jsonStr length -- > " + bytes.length);
httpURLConnection.setRequestProperty("Content-Length",String.valueOf(bytes.length));
//连接
httpURLConnection.connect();
//把数据给到服务
outputStream = httpURLConnection.getOutputStream();
outputStream.write(bytes);
outputStream.flush();
//拿结果
int responseCode = httpURLConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK) {
inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
Log.d(TAG,"result -- > " + bufferedReader.readLine());
}
} catch(Exception e) {
e.printStackTrace();
} finally {
IOUtils.ioClose(inputStream);
IOUtils.ioClose(outputStream);
}
}
}).start();
}
使用GsonFormat来生成以下类:
public class CommentItem {
public CommentItem(String articleId,String commentContent) {
this.articleId = articleId;
this.commentContent = commentContent;
}
private String articleId;
private String commentContent;
public String getArticleId() {
return articleId;
}
public void setArticleId(String articleId) {
this.articleId = articleId;
}
public String getCommentContent() {
return commentContent;
}
public void setCommentContent(String commentContent) {
this.commentContent = commentContent;
}
}
如果不会使用GsonFormat的,或者不会安装插件的同学,可以去看看AndroidStudio的课程
AndroidStudio奇淫技巧-掌握以后可以提升效率,还可以装逼
然后跑起来吧!
运行结果
result -- > {"success":true,"code":10000,"message":"评论成功:你的文章写得也太好了!","data":null}
后台服务器下载请看视频,或者跟着说明进行配置。