Android Studio中與網站通信

post方法

HttpURLConnection必須在子線程執行

/**
                     * 方法名: new Thread
                     * 作用: 開啓新的子線程,
                     * start(): 是準備運行子線程
                     * run(): 運行子線程
                     */
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String path = "https://網址";  //要提交的網址,如果是http需要android:usesCleartextTraffic="true"
                            try {
                                URL url = new URL(path);
                                HttpURLConnection conn = (HttpURLConnection) url.openConnection();  //得到conn對象
                                conn.setConnectTimeout(60000);  //連接服務器超時
                                conn.setRequestMethod("POST");  //設置請求模式
                                conn.setReadTimeout(60000);  //從服務器接收數據超時
                                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 設置發送的數據爲表單類型,會被添加到http body當中
                                //conn.setRequestProperty ("Content-Type", "application/json");
                                Gson gson = new Gson();
                                Person person = new Person();
                                person.setCha_xun("ceshi");
                                person.setKai_shi_shi_jian(shu_zi);
                                String data = gson.toJson(person); //將對象轉換爲JSON
                                conn.setRequestProperty("Content-Length", String.valueOf(data.length()));//設置發送數據的長度
                                conn.setDoOutput(true); //設置true表示連接爲輸出(提交),默認爲false.
                                conn.setUseCaches(false); //設置不用緩存
                                conn.setDoInput(true);  //設置true表示連接爲輸入(提交),默認爲true.
                                conn.getOutputStream().write(data.getBytes()); //寫入此連接的輸出流,我理解爲提交數據
                                int responseCode = conn.getResponseCode(); //從HTTP響應消息獲取狀態代碼
                                if (responseCode == 200) {
                                    InputStream inputStream = conn.getInputStream(); //從這個打開的連接讀取數據的輸入流(讀取服務器返回的數據)
                                    final String result = StreamUtils.readStream(inputStream); //解析數據
                                    runOnUiThread(new Runnable() { //在子線程操作UI更新的方法
                                        @Override
                                        public void run() {
                                            textView_cha_xun_fan_hui.setText(result);
                                        }
                                    });
                                } else {
                                    showToastInAnyThread("保存失敗");
                                }


                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

StreamUtils類

public class StreamUtils {
    public static String readStream(InputStream is){
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while(( len = is.read(buffer))!=-1){
                baos.write(buffer, 0, len);
            }
            is.close();
            String result = baos.toString();

            if(result.contains("gb2312")){
                return baos.toString("gb2312");
            }else{
                return result;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Bitmap readBitmap(InputStream is){
        return BitmapFactory.decodeStream(is);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章