Android6.0中把Apache HTTP Client所有的包与类都标记为deprecated不再建议使用所有跟HTTP相关的数据请求与提交操作都通过HttpURLConnection类实现,刚刚用HttpURLConnection给朋友做了一个通过GET请求并且实现json解析的列子大家先看看效果图
package com.haiwei.httptest;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView tv_content,tv_json;
private ProgressDialog dialog;
private HttpURLConnection conn;
private String testUrl = "http://ysdktest.qq.com/auth/qq_check_token/?timestamp=&appid=&sig=&openid=&openkey=&userip";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
tv_content = (TextView) findViewById(R.id.tv_content);
tv_json = (TextView) findViewById(R.id.tv_json);
dialog = new ProgressDialog(this);
dialog.setMessage("正在加载数据,请稍候...");
httpResponse();
}
private void httpResponse(){
dialog.show();
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(testUrl);
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(0);
}
}, 2000);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public void parseJsonClick(View view){
DataBean dataBean = new DataBean();
String json = tv_json.getText().toString().trim();
try {
JSONObject jsonObject = new JSONObject(json);
dataBean.setRet(jsonObject.getInt("ret"));
dataBean.setMsg(jsonObject.getString("msg"));
tv_content.setText("返回状态:" + dataBean.getRet() + "返回信息:" + dataBean.getMsg());
} catch (JSONException e) {
e.printStackTrace();
}
}
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
if (msg.what == 0) {
try {
int BUFFER_SIZE = 4096;
InputStream inputStream;
String resultData = "";
StringBuffer out = new StringBuffer();
byte[] b = new byte[BUFFER_SIZE];
inputStream = new BufferedInputStream(conn.getInputStream());
int n;
while ((n=inputStream.read(b))!=-1){
out.append(new String(b,0,n));
}
resultData = out.toString();
tv_json.setText(resultData+"");
} catch (IOException e) {
e.printStackTrace();
}
dialog.dismiss();
}
};
};
}
上面通过HttpURLConnection请求状态200为成功 400为失败 成功后通过handle发送通知 通过inputStream拼接为json字符串 解析式通过原生解析 记得在AndroidManifest中加入<uses-permission android:name="android.permission.INTERNET"/>网络访问权限 代码也非常简单 想信大家一看就很明白了