码迷,mamicode.com
首页 > 移动开发 > 详细

Android 通过HTTP POST请求互联网数据

时间:2015-11-18 14:04:04      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn).setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                new AsyncTask<String, Void, String>() {

                    @Override
                    protected String doInBackground(String... params) {
                        try {
                            URL url=new URL(params[0]);
                            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
                            
                            connection.setDoOutput(true);
                            connection.setRequestMethod("POST");
                            
                            OutputStreamWriter osw=new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
                            BufferedWriter bw=new BufferedWriter(osw);
                            bw.write("keyfrom=aiHttpGet&key=1989341286&type=data&doctype=json&version=1.1&q=post");
                            bw.flush();
                            
                            InputStream iStream=connection.getInputStream();
                            InputStreamReader isr=new InputStreamReader(iStream,"UTF-8");
                            BufferedReader br=new BufferedReader(isr);
                            String line;
                            while ((line=br.readLine())!=null) {
                                Log.i("get", line);
                            }
                            br.close();
                            isr.close();
                            iStream.close();
                        } catch (MalformedURLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        return null;
                    }
                }.execute("http://fanyi.youdao.com/openapi.do");
            }
        });
    }

API:http://fanyi.youdao.com/openapi

Android 通过HTTP POST请求互联网数据

标签:

原文地址:http://www.cnblogs.com/stareblankly/p/4974169.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!