Andriod調用http請求

          // 新建HttpPost對象
		HttpPost httpPost = new HttpPost(
				"http://180.153.1.1:8080/mybankGateway/gateway/queryProductType");

		// 參數列表
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("query", "工做日"));

		// 設置字符集
		HttpEntity entity = null;
		try {
			entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		// 設置參數實體
		httpPost.setEntity(entity);
		// 獲取HttpClient對象
		HttpClient httpClient = new DefaultHttpClient();
		// 鏈接超時
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
		// 請求超時
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				30000);
		try {
			// 獲取HttpResponse實例
			HttpResponse httpResp = httpClient.execute(httpPost);
			// 判斷是夠請求成功
			if (httpResp.getStatusLine().getStatusCode() == 200) {
				// 獲取返回的數據
				String result = EntityUtils.toString(httpResp.getEntity(),
						"UTF-8");
				Log.i("HttpPost", "HttpPost方式請求成功,返回數據以下:");
				Log.i("result", result);
				System.err.println(result);
			} else {
				Log.i("HttpPost", "HttpPost方式請求失敗");
			}
		} catch (ConnectTimeoutException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
相關文章
相關標籤/搜索