1、简介
通过 HttpURLConnection - Post 方式,访问服务器,并且传递json 参数,
同时获取从服务器返回的json数据
2、功能实现
1)、AndroidManifest.xml 添加权限
添加网络访问权限
<uses-permission android:name="android.permission.INTERNET" />
2)activity_main.xml 布局文件
就一个 按钮,一个 textview
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/btn_query"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="点击"
android:textSize="30dp"
android:onClick="onClick"
/>
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/et_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</ScrollView>
</LinearLayout>
2)MainActivity.java 功能文件
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity {
private String TAG = "MainActivity: ";
private TextView et_content;
private String url = "https://www.baidu.com/"; // 访问的 url
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_content = (TextView) findViewById(R.id.et_content);
}
@SuppressLint("StaticFieldLeak")
public void onClick(View view) throws UnsupportedEncodingException {
//创建一个json 数据
/* {
"name": "lum",
"age": 27,
"sex": "man"
}*/
JSONObject jsonParams = new JSONObject();
try {
jsonParams.put("name", "lum");
jsonParams.put("age", 27);
jsonParams.put("sex", "man");
} catch (JSONException e) {
e.printStackTrace();
}
new AsyncTask<String, String, String>() {
@Override
protected String doInBackground(String... params) {
StringBuffer buffer=new StringBuffer();
try {
Log.d(TAG, "params[0]: " + params[0] + " params[1]: " + params[1] );
//封装 url 对象
URL url = new URL(params[0]);
// 获取 http 链接对象
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
// 设置请求方式
conn.setRequestMethod("POST");
// 设置读写和请求的超时时间 5s
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
//设置链接是否可以输出
conn.setDoOutput(true);
//设置链接是否可以输入
conn.setDoInput(true);
//告诉服务端提交的数据类型(表单数据)
conn.setRequestProperty("Content-Type","application/json");
OutputStream output=conn.getOutputStream();
output.write(params[1].getBytes());// 向服务器传递参数
output.close();
// 获取状态码
int code = conn.getResponseCode();
Log.d(TAG,code+"");
if (code == 200) {//请求成功
Log.d(TAG,conn.getHeaderFields().toString());
// 获取相应消息的实体内容
InputStreamReader reader = new InputStreamReader(
conn.getInputStream());
char[] charArr = new char[1024 * 8];
int len = 0;
while ((len = reader.read(charArr)) != -1) { //获取服务器返回的 数据
// 字符型数组转换成字符串
String str = new String(charArr, 0, len);
// 在结尾追加字符串
buffer.append(str);
}
} else {
Log.d(TAG,"fail code is: " + code);
}
} catch (MalformedURLException e) {
e.printStackTrace();
Log.d(TAG,"访问目标失败 ");
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG,"读写数据流失败 ");
}
return buffer.toString();
}
protected void onPostExecute(String result) {
// 设置字体到边框
et_content.setText(result); //显示服务器返回的数据
};
}.execute(url,jsonParams.toString());
}
}