Android发送Post请求获取Json字符串

来源:互联网 发布:淘宝账号申请及注册 编辑:程序博客网 时间:2024/05/08 22:44

在android开发过程中,向后台发送post请求获取相应的json字符串是非常常见的操作,至于What does 'json' mean?(json是个啥?)这个问题还是交给不要脸的度娘或者总是死去活来的谷哥吧。本人在此只是简单介绍一下自己常用的方法,如有不足之处还望诸位指出。

首先奉上GetJson方法一个 

/** * 发送post请求获取json字符串 * @param url 网站 * @param params 参数List * @return json字符串 */private String GetJson(String url, List<NameValuePair> params) {HttpPost httpRequest = new HttpPost(url);/* * NameValuePair实现请求参数的封装 */String strResult = null;/* 添加请求参数到请求对象 */HttpParams httpParameters1 = new BasicHttpParams();HttpConnectionParams.setConnectionTimeout(httpParameters1, 10 * 1000);HttpConnectionParams.setSoTimeout(httpParameters1, 10 * 1000);//设置超时参数try {httpRequest.setParams(httpParameters1);httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));/* 发送请求并等待响应 */HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);/* 若状态码为200 ok */if (httpResponse.getStatusLine().getStatusCode() == 200) {/* 读返回数据 */strResult = EntityUtils.toString(httpResponse.getEntity());} else {// 获取出现错误}} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return strResult;}
需要向该方法中传递两个参数:url地址字符串和需要发送的键值对的list


切记要在Manifest文件中添加网络操作权限 <uses-permission android:name="android.permission.INTERNET"/>,否则就跟断网时没区别的。 将这句话写在application标签之前。

既然方法有了,网络操作权限也添加了,那我们不妨来实验一下

protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);textview=(TextView)findViewById(R.id.textview);List<NameValuePair> params=new ArrayList<NameValuePair>();params.add(new BasicNameValuePair(key1, value1));params.add(new BasicNameValuePair(key2, value2));result=GetJson(myurl, params);textview.setText(result);Log.v("PostGetJson",""+result);}
其中向params中添加的就是需要发送的键值对,可以根据需要添加任意对;myurl是后台的地址。试运行一下,报错了!!!什么情况!!!

根据报的错误可知,这是由于在主线程中进行了网络操作引起的,那我们就需要另辟一个线程来发送post请求

private Runnable getJson=new Runnable(){public void run() {// TODO Auto-generated method stubtry{result=GetJson(myurl, params);handler.sendEmptyMessage(0x00);}catch(Exception e){handler.sendEmptyMessage(0x01);}}};Handler handler=new Handler(){public void handleMessage(android.os.Message msg){if(msg.what==0x00){textview.setText(result);Log.v("PostGetJson",""+result);}else if(msg.what==0x01){Toast.makeText(getApplicationContext(), "获取失败", Toast.LENGTH_LONG).show();}}};

在新线程中进行post请求操作,在handler中将请求的结果显示出来。注意!在新开辟的线程中不能进行UI操作!

得到最终返回结果


已将源码上传,可以免费下载,希望大家能指出不足之处,帮助我改进!

点击打开链接

0 0