Android最基本的网络请求(json解析):httpget/httppost/AsyncTask
//不要忘了执行
(MyAsyncTask asyncTask=new MyAsyncTask();
asyncTask.execute();)
class MyAsyncTask extends AsyncTask<Void, Void, String>{
protected String doInBackground(Void... params) {
try {
//httpget请求
String path="http://v.juhe.cn/laohuangli/h?date="+URLEncoder.encode(data, "utf-8")+"&key=68a5d2578c4dedb4e2b7922148f70c24";
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet=new HttpGet(path);
HttpResponse httpResponse = httpClient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if(statusCode==200){
InputStream content = httpResponse.getEntity().getContent();
String str = streamToStr(content);
return str;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Gson gson=new Gson();
gson.fromJson(result, TimeTwo.class);
}
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//Url请求
public static void getInputStream(final String path,final Handler handler){
new Thread(){
public void run() {
try {
URL url=new URL(path);
HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
openConnection.setConnectTimeout(5000);
openConnection.setReadTimeout(5000);
int responseCode = openConnection.getResponseCode();
if(responseCode==200){
InputStream inputStream = openConnection.getInputStream();
String str = Streamtostr(inputStream);
Message msg = Message.obtain();
msg.obj=str;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
------------------------------------------------------------------------------------------------------------------------
// 创建一个客户端对象
HttpClient httpClient = new DefaultHttpClient();
// 创建post请求对象
HttpPost httpPost = new HttpPost(path);
// 创建一个参数的集合
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
// 添加参数 键值对方式
parameters
.add(new BasicNameValuePair("username", username));
parameters
.add(new BasicNameValuePair("password", password));
// 实例化实体对象
HttpEntity httpEntity = new UrlEncodedFormEntity(parameters);
// 设置实体内容
httpPost.setEntity(httpEntity);
// 执行post请求 获取响应
HttpResponse httpResponse = httpClient.execute(httpPost);
// 获取状态行对象
StatusLine statusLine = httpResponse.getStatusLine();
// 获取状态码
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
// 获取实体对象
HttpEntity entity = httpResponse.getEntity();
// 获取实体内容
InputStream inputStream = entity.getContent();
//转成字符串
String str = steamToStr(inputStream);
//发送给主线程
Message obtain = Message.obtain();
obtain.obj = str;
obtain.what = SUCCESS;
handler.sendMessage(obtain);