您的位置:首页 > 理论基础 > 计算机网络

使用HttpURLConnection请求Gson网络解析数据

2016-07-07 17:53 441 查看

解析 JSON 数据 使用官方提供的 JSONObject,也可以使用谷歌的开源库 GSON.

package com.gaoo.httpclientdemo;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class MainActivity extends AppCompatActivity {

Button send;
TextView show;
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);

if (msg.what == 0x123) {
String result = (String) msg.obj;
show.setText(result.toString());
}

}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

send = (Button) findViewById(R.id.send);
show = (TextView) findViewById(R.id.show);

send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendRequest();
Toast.makeText(MainActivity.this, "点我了", Toast.LENGTH_SHORT).show();
}
}
);
}

private void sendRequest() {
// 开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("http://10.0.3.2/dataJson.json");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
// 下面对获取到的输入流进行读取
BufferedReader reader = new BufferedReader(new
InputStreamReader(in));
String response = new String();
String line;
while ((line = reader.readLine()) != null) {
response += line;
}
Log.d("----response---  ", response);
parseJSONWithJSONObject(response);

Message message = new Message();
message.what = 0x123;
// 将服务器返回的结果存放到Message中
message.obj = response.toString();
mHandler.sendMessage(message);

} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}

private void parseJSONWithJSONObject(String jsonData) {

//使用 Gson 解析json数据
Gson gson = new Gson();

List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>() {}.getType());

for (int i = 0; i < appList.size(); i++) {

App app = appList.get(i);
Log.e("MainActivity", app.toString());
// Log.d("MainActivity", "id is " + app.getId() + " name is " + app.getName() + " version is " + app.getVersion());
}

//----------------------------------

// JSONObject 解析json数据
//        try {
//            JSONArray jsonArray = new JSONArray(jsonData);
//            for (int i = 0; i < jsonArray.length(); i++) {
//                JSONObject jsonObject = jsonArray.getJSONObject(i);
//
//                String id = jsonObject.getString("id");
//                String version = jsonObject.getString("version");
//                String name = jsonObject.getString("name");
//
//                Log.d("MainActivity", "id is " + id+" name is " + name+" version is " + version);
//            }
//
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }

//---------------------------------

}
}


使用的javaBean

package com.gaoo.httpclientdemo;

/**
* Created by Administrator on 2016/7/7.
*/
public class App {
public String id;
public String name;
public String version;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getVersion() {
return version;
}

public void setVersion(String version) {
this.version = version;
}

@Override
public String toString() {
return "App{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", version='" + version + '\'' +
'}';
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  gson 网络 数据 json