HttpURLConnection訪問Webapi代碼

雖然代碼差很少,可是稍微改了些,嘻嘻......很是感謝原帖主。java

下面是我改後的代碼。(嘻嘻,雖然改後變化不大)api

private static String URL = "http://xxx/api/v1/video/Register";
public void regist(){
	Map<String, Object> requestParamsMap = new HashMap<String, Object>();  
        requestParamsMap.put("username", "test11");  
        requestParamsMap.put("password", "111");  
        PrintWriter printWriter = null;  
        HttpURLConnection conn = null;
        BufferedReader bufferedReader = null;  
        StringBuffer responseResult = new StringBuffer();  
        StringBuffer params = new StringBuffer();  
        // 組織請求參數  
        Iterator it = requestParamsMap.entrySet().iterator();  
        while (it.hasNext()) {  
            Map.Entry element = (Map.Entry) it.next();  
            params.append(element.getKey());  
            params.append("=");  
            params.append(element.getValue());  
            params.append("&");  
        }  
        if (params.length() > 0) {  
            params.deleteCharAt(params.length() - 1);  
        }  
		try {
	        String newUrl = URL +"?"+ params;   //初次接觸這東西,就直接拼接在地址上了
			URL url = new URL(newUrl);
	        conn = (HttpURLConnection) url.openConnection();
	        conn.setRequestMethod("POST");// 提交模式
	        conn.setRequestProperty("Content-Type", "plain/text; charset=UTF-8");  
	        
	        // 設置通用的請求屬性  
            conn.setRequestProperty("accept", "*/*");  
            conn.setRequestProperty("connection", "Keep-Alive");  
            // 發送POST請求必須設置以下兩行  
            conn.setDoOutput(true);  
            conn.setDoInput(true);
            conn.connect();
            int responseCode = conn.getResponseCode();  
            if (responseCode != 200) {  
            	System.out.println("Not Success");
            } else {  
            	System.out.println("Success");
            }  
            // 定義BufferedReader輸入流來讀取URL的ResponseData  
            bufferedReader = new BufferedReader(new InputStreamReader(  
                    conn.getInputStream()));  
            String line;  
            while ((line = bufferedReader.readLine()) != null) {  
                responseResult.append("/n").append(line);  
            }  
			/* 將Response顯示於Dialog */
			showDialog("註冊成功" + responseResult.toString().trim());
			/* 關閉DataOutputStream */
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			conn.disconnect();  
            try {  
                if (printWriter != null) {  
                    printWriter.close();  
                }  
                if (bufferedReader != null) {  
                    bufferedReader.close();  
                }  
            } catch (IOException ex) {  
                ex.printStackTrace();  
            } 
		}
	}

原本不想直接把參數拼接在地址上的,但使用OutputStream輸入流總是報404,偷懶直接拼上了。app

但願能幫助到別人吧。ide

相關文章
相關標籤/搜索