布局
实现代码
/** * 当前案例:
* 上传姓名和年龄,返回JSON字符串
*/
public class PostActivity extends AppCompatActivity implements View.OnClickListener {
protected Button mPostBtn;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_post);
initView();
}
@Override public void onClick(View view) {
if (view.getId() == R.id.post_btn) {
doPost();
}
}
// 使用异步任务执行POST请求 private void doPost() {
String url = "http://localhost:8080/postdemo";
PostTask task = new PostTask(); task.execute(url);
}
private void initView() {
mPostBtn = (Button) findViewById(R.id.post_btn);
mPostBtn.setOnClickListener(PostActivity.this);
}
private class PostTask extends AsyncTask{
@Override
protected Person doInBackground(String... params) {
String requestUrl = params[0];
URL url = null;
try {
url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置POST请求
connection.setRequestMethod("POST");
// 设置可向服务器输出
connection.setDoOutput(true);
// 打开连接
connection.connect();
// 打开连接后,向服务端写要提交的参数
// 参数格式:“name=asdasdas&age=123123”
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("name=")
.append("wuyanzu")// 拼接自己传入的姓名
.append("&")
.append("age=")
.append("123");// 拼接自己传入的年龄
// 获取向服务器写数据的输出流
connection.getOutputStream()
.write(stringBuilder.toString().getBytes());
// 提交数据后,获取来自服务器的json数据
if (connection.getResponseCode() == 200) {
BufferedReader br = null;
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String json = "";
String line = "";
while ((line = br.readLine()) != null) {
json += line.trim();
}
// 解析
Gson gson = new Gson();
Person person = gson.fromJson(json, Person.class);
return person;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Person person) {
super.onPostExecute(person);
Log.d("1507", "name:" + person.getName() + ", age: " + person.getAge());
}
}
}
自定义Bean类
package net.bwie.network.bean;
public class Person {
private String name = "";
private String age = "";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
网友评论