Android的中http協議HttpURLConnection中post請求

public class MainActivity extends AppCompatActivity {
    private TextView textView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView=(TextView)findViewById(R.id.mytext);
        //異步任務;
        MyTask task=new MyTask();
        task.execute("");
    }
    class MyTask extends AsyncTask<String,Integer,String>{
        @Override
        protected String doInBackground(String... params) {
            //網絡請求
            return getPostData();
        }


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //json解析
            Gson gson=new Gson();
            DataBean bean=gson.fromJson(s,DataBean.class);
            String text=bean.result.data.get(0).imtro;
            //更新UI操作
            textView.setText(text);
        }
    }
    //通過post請求來從網絡讀取數據;
    private String getPostData(){
        String path="http://apis.juhe.cn/cook/query.php";


        try {
            String value="menu="+ URLEncoder.encode("白菜","utf-8")+"&key=13af589c334ec80c037688e927407966&rn=1";
            //post的URL不要加參數值;
            URL url=new URL(path);
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            //設置請求方式爲post;默認是get;
            connection.setRequestMethod("POST");
            //設置輸出數據
            connection.setDoOutput(true);
            //獲取一個輸出流,用來設置參數
            OutputStream outputStream=connection.getOutputStream();
            //將參數放入輸出流中;
            outputStream.write(value.getBytes());
            //獲取連接狀態碼
            int code=connection.getResponseCode();
            if(code==200){
                //獲取請求返回的數據
                InputStream inputStream=connection.getInputStream();
                //將輸入流轉換爲string
                BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
                String result="";
                String str=null;
                while((str=reader.readLine())!=null){
                    result+=str;
                }
                return  result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }




        return  null;
    }

}

不要忘了加權限

發佈了21 篇原創文章 · 獲贊 21 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章